如何使用与PowerShell相同的结构将HTML表转换为CSV文件

时间:2014-09-18 16:41:20

标签: html powershell web-scraping export-to-csv

使用Powershell,我可以拿到这个 - $ URL =" http://example.com/yyy.htm" $ OutputFile =" $ env:temp \ tempfile.xml"

# reading website data:
$data = Invoke-WebRequest -Uri $URL 

# get the first table found on the website and write it to disk:
@($data.ParsedHtml.getElementsByTagName("table"))[0].OuterHTML | Set-Content -Path $OutputFile

现在我希望将此表转换为CSV ...我该怎么做?

表示例 -

Datacenter | FirstDNS | SecondDNS | ThirdDNS | FourthDNS
-----------------------------------------------------------
NewYork    | 1.1.1.1  | 2.2.2.2   |3.3.3.3   | 4.4.4.4
India      | 1.2.3.4  | 3.2.6.5   |8.2.3.7   | 8.3.66.1

2 个答案:

答案 0 :(得分:2)

这是一个将HTML表格转换为PSObjects的解决方案,然后您可以将其导入Export-CSV或执行您需要的任何操作。 请注意:这不是一个干净的解决方案;它只是简单的场景,但有很多问题:

  • 无法处理特殊字符( 除外),要使其正常工作,您需要在DocType实体地图中添加新定义根据要求)
  • 无法应对colspanrowspan;假设所有表格在每一行中的列数与标题中的列数相同(如果列数超过标题,则会进行调整以防止错误;但在这种情况下,您可能仍然会出现错位)
  • 我在转换为XML之前清理HTML的技术是使用正则表达式而不是解析库;所以那里可能会有意想不到的问题。
function ConvertFrom-HtmlTableRow {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        $htmlTableRow
        ,
        [Parameter(Mandatory = $false, ValueFromPipeline = $false)]
        $headers
        ,
        [Parameter(Mandatory = $false, ValueFromPipeline = $false)]
        [switch]$isHeader

    )
    process {
        $cols = $htmlTableRow | select -expandproperty td
        if($isHeader.IsPresent) {
            0..($cols.Count - 1) | %{$x=$cols[$_] | out-string; if(($x) -and ($x.Trim() -gt [string]::Empty)) {$x} else {("Column_{0:0000}" -f $_)}} #clean the headers to ensure each col has a name        
        } else {
            $colCount = ($cols | Measure-Object).Count - 1
            $result = new-object -TypeName PSObject
            0..$colCount | %{
                $colName = if($headers[$_]){$headers[$_]}else{("Column_{0:00000} -f $_")} #in case we have more columns than headers 
                $colValue = $cols[$_]
                $result | Add-Member NoteProperty $colName $colValue
            } 
            write-output $result
        }
    }
}

function ConvertFrom-HtmlTable {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        $htmlTable
    )
    process {
        #currently only very basic <table><tr><td>...</td></tr></table> structure supported
        #could be improved to better understand tbody, th, nested tables, etc

        #$htmlTable.childNodes | ?{ $_.tagName -eq 'tr' } | ConvertFrom-HtmlTableRow

        #remove anything tags that aren't td or tr (simplifies our parsing of the data
        [xml]$cleanedHtml = ("<!DOCTYPE doctypeName [<!ENTITY nbsp '&#160;'>]><root>{0}</root>" -f ($htmlTable | select -ExpandProperty innerHTML | %{(($_ | out-string) -replace '(</?t[rdh])[^>]*(/?>)|(?:<[^>]*>)','$1$2') -replace '(</?)(?:th)([^>]*/?>)','$1td$2'})) 
        [string[]]$headers = $cleanedHtml.root.tr | select -first 1 | ConvertFrom-HtmlTableRow -isHeader
        if ($headers.Count -gt 0) {
            $cleanedHtml.root.tr | select -skip 1 | ConvertFrom-HtmlTableRow -Headers $headers | select $headers
        }
    }
}

clear-host

[System.Uri]$url = 'https://en.wikipedia.org/wiki/List_of_countries_by_carbon_dioxide_emissions' 
$rqst = Invoke-WebRequest $url 
$rqst.ParsedHtml.getElementsByTagName('table') | ConvertFrom-HtmlTable 

仅供参考:我还在CodeReview上发布了此代码的早期版本,因此请查看是否有人建议有任何改进。

答案 1 :(得分:0)

使用Tee-Object输出文件,然后可以在此之后输出到Export-CSV:

@($data.ParsedHtml.getElementsByTagName("table"))[0].OuterHTML | Tee-Object -FilePath $OutputFile | Export-CSV $env:temp\tempfile.csv -notype