在脚本中使用GetElementsByClassName

Raf*_*lGP 15 powershell

我正在尝试编写PowerShell脚本,以便从网站中获取名为"newstitle"的所有类中的文本.

这就是我所拥有的:

function check-krpano {
    $geturl=Invoke-WebRequest http://krpano.com/news/
    $news=$geturl.parsedhtml.body.GetElementsByClassName("newstitle")[0]
    Write-Host  "$news"
}

check-krpano
Run Code Online (Sandbox Code Playgroud)

它显然需要更多的调整,但到目前为止,它不起作用.

我设法使用GetElementById编写脚本,但我不知道GetElementsByClassName的语法,说实话,我无法找到有关它的更多信息.

注意:

我已经勾选了我的问题的正确答案,但这不是我选择在我的脚本中使用的解决方案.

虽然我能够使用2种方法在包含某个类的标记中找到内容,但它们搜索链接的速度要慢得多.

这是使用Measure-Command的输出:

  • 使用parsedhtml.body - > 29.6秒搜索包含类'newstitle'的div
  • 使用Allelements搜索包含"newstitle"类的开发者 - > 10.4秒
  • 搜索其元素'href'包含#news - > 2.4秒的链接

所以我将Links方法的答案标记为有用.

这是我的最终剧本:

function check-krpano {
    Clear-Host
    $geturl=Invoke-WebRequest http://krpano.com/news
    $news = ($geturl.Links |Where href -match '\#news\d+' | where class -NotMatch 'moreinfo+' )
    $news.outertext | Select-Object -First 5
}

check-krpano
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 18

如果你弄清楚如何使GetElementsByClassName起作用,我想知道.我昨天碰到了这个并且没时间了,所以我提出了一个解决方法:

$geturl.ParsedHtml.body.getElementsByTagName('div') | 
    Where {$_.getAttributeNode('class').Value -eq 'newstitle'}
Run Code Online (Sandbox Code Playgroud)

  • 看起来像`getElementsByTagName()`中的一个错误.但是,我刚刚遇到[这个答案](http://stackoverflow.com/a/9059206/1630171),它建议这样的事情:`$ geturl.AllElements | ?{$ _.Class -eq'newstitle'} | 选择innerText`.可能会更优雅一点. (3认同)

Don*_*ank 18

getElementsByClassName不会直接返回数组,而是通过COM代理结果.如您所知,[]运算符不会自动转换为数组.您可以使用列表评估语法,@()首先强制它到数组,以便您可以访问单个元素:

@($body.getElementsByClassName("foo"))[0].innerText
Run Code Online (Sandbox Code Playgroud)

另外,如果您使用对象管道,则会自动执行转换,例如:

$body.getElementsByClassName("foo") | Select-Object -First 1
Run Code Online (Sandbox Code Playgroud)

它也可以使用foreach构造自动执行:

foreach ($element in $body.getElementsByClassName("foo"))
{
    $element.innerText
}
Run Code Online (Sandbox Code Playgroud)