You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell爬取网页表格并保存为CSV至指定目录

解决PostgreSQL安全页面表格数据爬取并导出CSV问题

原代码存在重复执行目录创建、网页请求的冗余操作,且未正确定位表格数据并提取字段值。以下是修正后的完整代码及说明:

关键修改点

  • 移除重复的目录创建与网页请求代码,避免冗余操作
  • 正确定位页面中的安全公告表格,遍历表格行提取每列数据
  • 将每行数据封装为自定义对象,确保Export-Csv能正确识别字段并写入

修正后的代码

# 创建带日期的目标目录
$destination = 'C:\Temp\{0:MMM dd}' -f (Get-Date)
$null = New-Item -Path $destination -ItemType Directory -Force
$outFile = Join-Path -Path $destination -ChildPath 'Demo.csv'

$url = 'https://www.postgresql.org/support/security/'
try {
    $req = Invoke-WebRequest -Uri $url -Method Get -ErrorAction Stop
}
catch {
    Write-Warning "请求失败: $_"
    exit 1
}

if ($req.StatusCode -ne 200) {
    Write-Warning "错误: 网站返回状态码 $($req.StatusCode)"
    exit 1
}

# 定位安全公告表格并提取数据
$table = $req.ParsedHtml.getElementsByTagName('table') | Where-Object {
    # 通过相邻的h2标题确认目标表格(安全公告表格在"Security Vulnerabilities"标题下方)
    $previousSibling = $_.previousSibling
    while ($previousSibling -and $previousSibling.tagName -ne 'H2') {
        $previousSibling = $previousSibling.previousSibling
    }
    $previousSibling.innerText -eq 'Security Vulnerabilities'
}

if (-not $table) {
    Write-Warning "未找到目标表格"
    exit 1
}

# 遍历表格行(跳过表头)
$table.getElementsByTagName('tr') | Select-Object -Skip 1 | ForEach-Object {
    $cells = $_.getElementsByTagName('td')
    if ($cells.Count -ge 4) {
        [PSCustomObject]@{
            CVE_ID             = $cells[0].innerText.Trim()
            Severity           = $cells[1].innerText.Trim()
            Affected_Versions  = $cells[2].innerText.Trim()
            Description        = $cells[3].innerText.Trim()
            Fixed_In           = if ($cells.Count -ge 5) { $cells[4].innerText.Trim() } else { '' }
        }
    }
} | Export-Csv -Path $outFile -UseCulture -NoTypeInformation

Write-Host "数据已成功导出到 $outFile"

代码说明

  1. 错误处理优化:使用try/catch捕获网页请求异常,避免因网络问题导致脚本崩溃
  2. 表格定位:通过表格前的H2标题确认目标表格,避免页面结构微调时定位失效
  3. 数据提取:遍历表格每行,将每列文本封装为带明确字段名的自定义对象,确保CSV输出的字段清晰清晰
  4. 兼容性处理:判断单元格数量,避免因部分行结构差异导致的错误

内容的提问来源于stack exchange,提问作者Meenkashi Sundaram Udayappan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:48:14