PowerShell - 无法引用.getElementsByTagName()返回的数组中元素的属性

时间:2016-06-29 21:54:24

标签: html powershell

我正在通过.getElementsByTagName()从网页中检索元素数组。然后我循环遍历数组并打印出元素的标题:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>Notice only the simply-drop-down class with the appropriate data attribute is red.</pre>
<div class='simply-drop-menu' data-type-simply-menu="user_friends-request">class='simply-drop-menu' data-type-simply-menu="user_friends-request"</div>
<div class='simply-drop-menu'>class='simply-drop-menu'</div>
<div data-type-simply-menu="user_friends-request">data-type-simply-menu="user_friends-request"</div>
<div class='simply-drop-menu' data-type-simply-menu="user_friends-foo">class='simply-drop-menu' data-type-simply-menu="user_friends-foo"</div>

这很有效。然而,for循环更适合我的需要,这似乎只打印出空行:

$links = $ie.document.GetElementsByTagName("a")
Foreach($link in $links)
{
    $link.title
}

为什么第二个循环不打印标题?

2 个答案:

答案 0 :(得分:1)

下面的6种方法都打印了所有链接标题,但Select-Object除了title属性时还会打印一个空行:

$requestUri = "http://google.com"

$ie = New-Object -ComObject "InternetExplorer.Application"
$ie.Navigate($requestUri)
while($ie.Busy) { Start-Sleep -Milliseconds 250 }
$links = $ie.Document.getElementsByTagName("a")

Write-Warning "ForEach-Object:"
$links | ForEach-Object { $_.title }

Write-Warning "Select-Object:"
$links | Select-Object title

Write-Warning "foreach:"
foreach($link in $links) { $link.title }

Write-Warning "for (from 0):"
for($i = 0; $i -lt $links.Length; $i++) {
    $links[$i].title
}

Write-Warning "for (from 1):"
for($i = 1; $i -le $links.Length; $i++) {
    $links[$i].title
}

Write-Warning "while:"
$i = 0
while($links[$i]) {
    $links[$i].title
    $i++
}

$ie.Quit()

你可以尝试在你的系统上运行吗?

答案 1 :(得分:-1)

我猜是$links = $ie.document.GetElementByTagName("a")和 和$links = $varDiv.GetElementsByTagName("a")不等同,因为它们没有为您提供相同的对象类型。