【发布时间】:2020-04-22 18:02:08
【问题描述】:
我有以下 html 表格:
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<h2>HTML Table</h2>
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
</body>
我想匹配所有出现的<th>table headers</th> 和<td>table data</td>。
对于<td>table data</td>,我已经成功调用了一个webrequest,得到了html文件,现在正在提取表格内容:
$Table = $Data.Content
$NumberOfColumns = ($Table | Select-String "<th>" -AllMatches).Matches.Count
$NumberOfRows = ($Table | Select-String "<td>" -AllMatches).Matches.Count
$AllMatches = @()
$Found = $Table -match "(?<=<td>)[a-zA-Z0-9 _-]{1,99}(?=</td>)"
ForEach ($Row in $NumberOfRows)
{
If ($Found -eq $True)
{
$AllMatches += $Matches
}
}
$AllMatches
我得到这个输出:
Name Value
---- -----
0 Alfreds Futterkiste
我想获取嵌入在th 和td 中的所有匹配项的列表(我正在运行Powershell Core 6.2,因此ParsedHtml 方法不是一个选项。我想解析表格手动)。
非常感谢任何建议。
【问题讨论】:
-
Parsing HTML with regex is a hard job HTML 和正则表达式不是好朋友。使用解析器,它更简单、更快且更易于维护。 gallery.technet.microsoft.com/Powershell-Tip-Parsing-49eb8810
-
这适用于 PSCore 6.2 吗?我不相信它依赖于 IE 解析器,还是我错了?
-
HTMLFileCOM 对象应该可以在任何常规 Windows 系统上使用,但它不会为您提供最新的 DOM API 方法(querySelector之类的东西将不可用)。 -
除此之外,使用 HTML Agility Pack(或其他解析器,尽管我相信这是 .NET 中最成熟、最通用的解析器)是您唯一明智的选择。
-
使用称职的 HTML 解析器。 stackoverflow.com/a/1732454/447901
标签: regex powershell