我有以下代码:
$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
返回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
[1]值得注意的是相对于经由支撑XPath查询.SelectSingleNode()
和.SelectNodes()
方法,经由暴露子节点.ChildNodes
集合,并且提供.InnerHtml
/ .OuterHtml
/.InnerText
属性。提供了和方法,而不是支持子元素名称的索引器。.Element(<name>)
.Elements(<name>)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句