我有以下代码:
$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"
}
该代码在 Windows Powershell 5.1 上运行良好,但在 Powershell Core 7
$_.tBodies[0].rows
上运行良好返回空值。那么,如何在 PS 7 中访问 HTML 表格的行?
最佳答案
从 7.0 开始,PowerShell [Core] 没有内置 HTML 解析器 .
您必须依赖 第三方解决方案 ,例如 PowerHTML
module 包装 HTML Agility Pack .
对象模型与 Windows PowerShell 中可用的基于 Internet Explorer 的工作方式不同;它类似于标准 System.Xml.XmlDocument
提供的 XML DOM类型[1];见 the documentation以及下面的示例代码。
# 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
[1] 特别是关于通过
.SelectSingleNode()
支持 XPath 查询和 .SelectNodes()
方法,通过 .ChildNodes
暴露子节点收藏、提供.InnerHtml
/.OuterHtml
/.InnerText
特性。代替支持子元素名称的索引器,方法 .Element(<name>)
和 .Elements(<name>)
提供。
关于html - 如何使用 Powershell Core 7 解析 HTML 表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60655737/