mar*_*ark 4 html powershell powershell-core
我有以下代码:
$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 表格的行?
从 7.0 开始,PowerShell [Core] 没有内置 HTML 解析器。
您必须依赖第三方解决方案,例如包装HTML Agility Pack的PowerHTML模块。
该对象模型的工作比在Windows PowerShell中可用的基于Internet Explorer的一个不同; 它类似于标准System.Xml.XmlDocument类型[1]提供的 XML DOM ;请参阅下面的文档和示例代码。
# Install the module on demand
If (-not (Get-Module -ErrorAction Ignore -ListAvailable PowerHTML)) {
Write-Verbose "Installing PowerHTML module for the current user..."
Install-Module PowerHTML -ErrorAction Stop
}
Import-Module -ErrorAction Stop PowerHTML
# Create a sample HTML file with a table with 2 columns.
Get-Item $HOME | Select-Object Name, Mode | ConvertTo-Html > sample.html
# Parse the HTML file into an HTML DOM.
$htmlDom = ConvertFrom-Html -Path sample.html
# Find a specific table by its column names, using an XPath
# query to iterate over all tables.
$table = $htmlDom.SelectNodes('//table') | Where-Object {
$headerRow = $_.Element('tr') # or $tbl.Elements('tr')[0]
# Filter by column names
$headerRow.ChildNodes[0].InnerText -eq 'Name' -and
$headerRow.ChildNodes[1].InnerText -eq 'Mode'
}
# Print the table's HTML text.
$table.InnerHtml
# Extract the first data row's first column value.
# Note: @(...) is required around .Elements() for indexing to work.
@($table.Elements('tr'))[1].ChildNodes[0].InnerText
Run Code Online (Sandbox Code Playgroud)
[1]值得注意的是相对于经由支撑XPath查询.SelectSingleNode()和.SelectNodes()方法,经由暴露子节点.ChildNodes集合,并且提供.InnerHtml/ .OuterHtml/.InnerText属性。而不是提供支持子元素名称、方法和的索引器。.Element(<name>).Elements(<name>)