html - 如何使用 Powershell Core 7 解析 HTML 表格?

标签 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"
    }

该代码在 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/

相关文章:

php - 更改读取文件文本输出的颜色

class - 在实例化时为 PowerShell 类设置属性

Powershell不扩展Foreach-Object内的变量字符串

powershell - 为什么从Powershell传递args会在脚本本身内部工作时出错

linux - 从 Powershell 确定操作系统版本、Linux 和 Windows

javascript - 如何查看 Internet Explorer 的 javascript 生成的 html?

javascript - 尝试在字符串内部使用 FOR 循环。 (JS,jQuery)

javascript - JavaScript Blob 对象什么时候被垃圾回收?

docker - 如何从 dotnet core 2.2 和 powershell core 创建 docker 镜像?

powershell - `Start-Process` 找不到存在于 PATH 中的文件,即使给定了文件的绝对路径