Web Scraping在PowerShell监控页面中

时间:2011-10-11 11:28:40

标签: html powershell status

我希望能够监控我的打印机状态网页,并在墨水量低于25%时通过电子邮件发送给我。我很确定这可以在Powershell中完成,但我对如何做到这一点感到茫然。

这是有问题的网页HTML:

<h2>Supply Status</h2>

    <table class="matrix">
                <thead>
    <tr>
        <th>Supply Information</th>
        <th>Status</th>
    </tr>
    </thead>

    <tbody>
    <tr>
        <td>Black Toner</td>
        <td>End of life</td>
    </tr>
    <tr>
        <td>Cyan Toner</td>

        <td>Under 25%</td>
    </tr>
    <tr>
        <td>Magenta Toner</td>
        <td>Under 25%</td>
    </tr>
    <tr>

        <td>Yellow Toner</td>
        <td>Under 25%</td>
    </tr>
    </tbody>

    </table>
    <p>

感谢。

亚当

2 个答案:

答案 0 :(得分:3)

在@Joey的答案的基础上,用HTML Agility Pack进行调整。

$html = new-object HtmlAgilityPack.HtmlDocument 
$result = $html.Load("http://full/path/to/file.htm") 
$colors = $html.DocumentNode.SelectNodes("//table[@class='matrix']//tbody/tr")
$result = $colors | % { 
    $color = $_.SelectSingleNode("td[1]").InnerText
    $level = $_.SelectSingleNode("td[2]").InnerText
    new-object PsObject -Property @{ Color = $color; Level = $level; } | 
        Select Color,Level
}
$result | Sort Level | ft -a

这假设您已经将HTML Agility Pack加载到PowerShell中。我的个人资料中载有:

[System.Reflection.Assembly]::LoadFrom( 
      (join-path $profileDirectory HtmlAgilityPack) 
       + "\HtmlAgilityPack.dll" ) | Out-Null

使用提供的示例HTML,您的输出如下:

output from PowerShell script

此时,您有输出并可以通过电子邮件发送出去。

答案 1 :(得分:1)

最简单的方法可能是您可以在PowerShell中导入的HTML Agility PackLee Holmes有一篇简短的文章,展示了一个简单的例子。基本上,您正在使用类似XML的API来访问HTML DOM。