首页 > 解决方案 > 如何使用 Powershell Core 7 解析 HTML 表格?

问题描述

我有以下代码:

    $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 表格的行呢?

标签: htmlpowershellpowershell-core

解决方案


从 7.0 开始,PowerShell [Core] 不附带内置的 HTML 解析器

您必须依赖第三方解决方案,例如包装HTML Agility Pack的PowerHTML模块

对象模型的工作方式与 Windows PowerShell 中基于 Internet Explorer的对象模型不同;类似于标准类型[1]提供的XML System.Xml.XmlDocumentDOM ;请参阅下面的文档和示例代码。

# 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()and.SelectNodes()方法支持 XPath 查询、通过集合公开子节点.ChildNodes以及提供//.InnerHtml属性。代替支持子元素名称的索引器,提供了方法和方法。.OuterHtml.InnerText.Element(<name>).Elements(<name>)


推荐阅读