【问题标题】:Getting HtmlDocument from string without using browser control在不使用浏览器控件的情况下从字符串获取 HtmlDocument
【发布时间】:2012-05-24 21:07:52
【问题描述】:

我使用 WebClient 获取网页的 html 代码(作为字符串)。

但是我想把它变成一个 HtmlDocument 对象,这样我就可以使用这个类提供的 DOM 特性。目前我知道如何做到这一点的唯一方法是使用浏览器控件,如下所示:

            string pageHtml = client.DownloadString(url);

            browser.ScriptErrorsSuppressed = true;

            browser.DocumentText = pageHtml;

            do
            {
                Application.DoEvents();

            } while (browser.ReadyState != WebBrowserReadyState.Complete);

            return browser.Document;

还有其他方法吗?我知道还有其他可用的浏览器控件,但有没有更简单的方法?

【问题讨论】:

    标签: c# browser dom


    【解决方案1】:

    您可以使用HtmlAgilityPack .... 例如:

    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(html);
    
    var results = doc.DocumentNode
        .Descendants("div")
        .Select(n => n.InnerText);
    

    【讨论】:

    • 我会考虑这一点,但是我已经有很多使用 HtmlDocument 类的代码,而且我更多的是寻找可以插入而不需要更改所有内容的东西。
    【解决方案2】:

    我知道这是一篇旧帖子,但我的回复是为像我一样来到这里的其他人提供的

    如果您想使用代码 .NET here is what you have to do 来做到这一点

    public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
            {
                WebBrowser browser = new WebBrowser();
                browser.ScriptErrorsSuppressed = true;
                browser.DocumentText = html;
                browser.Document.OpenNew(true);
                browser.Document.Write(html);
                browser.Refresh();
                return browser.Document;
            }
    

    【讨论】:

      【解决方案3】:

      我知道这是一个老话题,我的解决方案:

      public static class HtmlHelpr{
      
              public static HtmlDocument HtmlDocumentFromFile(this string PathToHtml){
                  using(WebBrowser wb = new WebBrowser()){            
                      string s = File.ReadAllText(PathToHtml);
                      wb.ScriptErrorsSuppressed = true;
                      wb.DocumentText = s;
                      var hd = wb.Document;
                      hd.Write(s);
                      return  hd;
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2019-01-16
        • 2018-08-04
        • 1970-01-01
        • 2016-01-10
        • 2018-06-06
        • 1970-01-01
        • 2012-05-10
        • 2013-04-24
        • 2023-03-18
        相关资源
        最近更新 更多