主要问题源于 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>
时元素,我没有得到任何 child ,因此我不能选择 <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
等于假。
从我提供的 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>
最佳答案
实际上我不是 PowerShell 的用户,但根据 this blog post ,你可能想尝试这样的事情:
[HtmlAgilityPack.HtmlNode.ElementsFlags]::Remove("form")
关于html - Powershell 2.0 - 使用 HtmlAgilityPack 获取 FORM 元素的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24939749/