【发布时间】:2014-09-16 08:45:28
【问题描述】:
主要问题源于默认情况下 HtmlAgiltyPack 不会从 <form> 元素中获取子节点。请参阅How to get all input elements in a form with HtmlAgilityPack without getting a null reference error 了解更多信息。
问题是,该链接显示了如何在 C# 中修复该问题,但我需要在 PowerShell 中修复它。有什么想法吗?
我将简化我的 HTML
<form method="POST" action="post.aspx" id="form">
<div>
<input type="hidden" name="test1" id="test1" value="1" />
</div>
<input type="text" name="test2" id="test2" value="12345" />
</form>
现在我看到,当我选择 <form> 元素时,我没有返回任何子元素,因此我无法选择 <input> 元素。
Add-Type -Path "C:\Program Files (x86)\HtmlAgilityPack\HtmlAgilityPack.dll"
$HTMLDocument = New-Object HtmlAgilityPack.HtmlDocument
$HTMLDocument.Load("C:\users\smithj\Desktop\test2.html")
$inputNodes=$HTMLDocument.DocumentNode.SelectNodes("//form")
$inputNodes
# Output shortened to show important bits ...
ChildNodes : {}
HasChildNodes : False
可以看到HasChildNodes等于false。
从我提供的 C# 链接中,我不知何故需要运行 HtmlNode.ElementsFlags.Remove("form");,但我不知道在 PowerShell 中输入什么是等效的。
再次感谢!
编辑
感谢 har07 为我指明了正确的方向。 [HtmlAgilityPack.HtmlNode]::ElementsFlags.Remove("form") 是我需要运行的。
请注意,我需要在加载 HTML 之前运行该命令。
> Add-Type -Path ".\Net40\HtmlAgilityPack.dll"
> [HtmlAgilityPack.HtmlNode]::ElementsFlags.Remove("form")
True
>
> $HTMLDocument = New-Object HtmlAgilityPack.HtmlDocument
> $HTMLDocument.Load(".\file.html")
> $HTMLDocument.DocumentNode.SelectNodes("//form")
# Output shortened to show important bits ...
ChildNodes : {#text, div, #text, input...}
HasChildNodes : True
OuterHtml : <form method="POST" action="post.aspx" id="form">
<div>
<input type="hidden" name="test1" id="test1" value="1">
</div>
<input type="text" name="test2" id="test2" value="12345">
</form>
【问题讨论】:
标签: html powershell html-parsing html-agility-pack