html - 如何使用 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 表格的行呢?
解决方案
从 7.0 开始,PowerShell [Core] 不附带内置的 HTML 解析器。
您必须依赖第三方解决方案,例如包装HTML Agility Pack的PowerHTML
模块。
对象模型的工作方式与 Windows PowerShell 中基于 Internet Explorer的对象模型不同;类似于标准类型[1]提供的XML System.Xml.XmlDocument
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] 特别是关于通过.SelectSingleNode()
and.SelectNodes()
方法支持 XPath 查询、通过集合公开子节点.ChildNodes
以及提供//.InnerHtml
属性。代替支持子元素名称的索引器,提供了方法和方法。.OuterHtml
.InnerText
.Element(<name>)
.Elements(<name>)
推荐阅读
- java - 在tomcat中,如何在其他项目中获取类的注释
- ruby-on-rails - 使用 remotipart gem 和 Paperclip 在 Ruby on Rails 中上传图像
- mysql - SQL选择两列组合的最高行
- c - 试图打印出用户空间内存的内容
- c++ - 从 C++ 服务器获取
- awk - 如何使用 AWK 用空格右填充字段
- python - 使用 sklearn 进行预测建模管道
- angular - Angular 5 ngFor 在表单标签中选择选项 ngModel
- nginx - Nginx 代理通行证配置
- android - 如何从自定义 Listview 中的 AlertDialog 获取数据?