在PowerShell 3.0中使用以下代码时
PS> $data = Invoke-Webrequest -Uri stackoverflow.com
PS> $data.ParsedHtml.getElementsByTagName("div")
Run Code Online (Sandbox Code Playgroud)
我收到这个警告:
Windows安全警告 - 要允许此网站为您提供个性化信息,您是否允许它在您的计算机上放置一个小文件(称为cookie)?
我真的想抑制此消息或添加代码来处理cookie,因此可以安排代码.
我曾尝试在IE中信任该网站,允许使用cookie,甚至降低"用户帐户控制设置",但无济于事.
我可以使用PowerShell来解析HTML页面
PS > $foo = Invoke-WebRequest http://example.com
PS > $foo.Links.Count
1
Run Code Online (Sandbox Code Playgroud)
但是如果我下载页面
PS > Invoke-WebRequest -OutFile example.htm http://example.com
Run Code Online (Sandbox Code Playgroud)
然后尝试解析下载的页面,它会产生意想不到的结果
PS > $foo = Invoke-WebRequest file://$pwd/example.htm
PS > $foo.Links.Count
0
Run Code Online (Sandbox Code Playgroud)
如何解析本地下载的页面?
$wc = New-Object System.Net.WebClient
$DownloadString = $wc.DownloadString("http://www.example.com")
$HTML = New-Object -ComObject "HTMLFile"
$HTML.IHTMLDocument2_write($DownloadString)
Run Code Online (Sandbox Code Playgroud)
运行服务器脚本
Major Minor Build Revision
----- ----- ----- --------
5 1 14409 1005
Run Code Online (Sandbox Code Playgroud)
开发PC
Major Minor Build Revision
----- ----- ----- --------
5 1 15063 502
Run Code Online (Sandbox Code Playgroud)
我的Windows 10开发PC在上面的代码中运行良好.我想在我的Server 2008 R2 x64机器上运行它.我将其升级到PowerShell v5.我得到以下内容:
方法调用失败,因为[System .__ ComObject]不包含名为"IHTMLDocument2_write"的方法.
后来......
Unable to find type [mshtml.HTMLDocumentClass].
Run Code Online (Sandbox Code Playgroud) powershell internet-explorer ihtmldocument2 windows-server powershell-5.0
我有以下代码:
$html = New-Object -ComObject "HTMLFile"
$source = Get-Content -Path $FilePath -Raw
try
{
$html.IHTMLDocument2_write($source) 2> $null
}
catch
{
$encoded = [Text.Encoding]::Unicode.GetBytes($source)
$html.write($encoded)
}
$t = $html.getElementsByTagName("table") | Where-Object {
$cells = $_.tBodies[0].rows[0].cells
$cells[0].innerText -eq "Name" -and
$cells[1].innerText -eq "Description" -and
$cells[2].innerText -eq "Default Value" -and
$cells[3].innerText -eq "Release"
}
Run Code Online (Sandbox Code Playgroud)
该代码在 Windows Powershell 5.1 上运行良好,但在 Powershell Core 7 上$_.tBodies[0].rows
返回 null。
那么,如何在 PS 7 中访问 HTML 表格的行?