【问题标题】:How to set Encoding for HtmlAgilityPack HtmlDocument如何为 HtmlAgilityPack HtmlDocument 设置编码
【发布时间】:2011-09-20 22:22:28
【问题描述】:

这是我的代码:

HtmlWeb hw = new HtmlWeb();

HtmlAgilityPack.HtmlDocument htmlDoc = hw.Load(@"www.SomeForeignURL.com");

返回的 HTML 页面包含看起来很奇怪的字符,我想将返回的文档的编码指定为 UTF-8。我该如何解决这个问题?

(尝试像这样加载文档:htmlDoc.Load("url", Encoding.UTF8) 但它返回一个错误,指出不支持 URI 或类似的东西。)

【问题讨论】:

    标签: html encoding load


    【解决方案1】:

    它可能没有那么有用,但我遇到了一个问题,即 Load() 方法静默失败,可能无法检测到格式,并通过首先将文件加载到字符串中来解决它(我使用另一个函数来下载文件)。然后我使用了 LoadHTML() 方法。我迟到了一年回答,我使用的是 powershell 而不是 C#,但提示可能仍然适用。

    参见倒数第二行:它只是将文件读入字符串并传递给 LoadHTML()

    #  http://www.leeholmes.com/blog/2010/03/05/html-agility-pack-rocks-your-screen-
    
    scraping-world/
    function DownloadFile {
    Param([Parameter(mandatory=$true)]$source , 
        [Parameter(mandatory=$true)]$destination) 
    
    
        $wc = New-Object System.Net.WebClient
        $wc.DownloadFile($source, $destination)
    }
    
    $erroractionpreference = 'stop'
    Set-Strictmode -version 2
    
    DownloadFile  "http://someurl/index.php?action=searchplayer&server=0&player=%" "$pwd\all.php"
    
    $types = add-type -Path .\agilitypack\HtmlAgilityPack.dll
    $doc = New-Object HtmlAgilityPack.HtmlDocument 
    $doc.LoadHtml([string](get-content .\all.html))
    $doc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      相关资源
      最近更新 更多