【问题标题】:HtmlAgilityPack HtmlWeb.Load returning empty DocumentHtmlAgilityPack HtmlWeb.Load 返回空文档
【发布时间】:2012-11-04 05:28:42
【问题描述】:

过去 2 个月我一直在 Web 爬虫应用程序中使用 HtmlAgilityPack,加载网页没有问题。

现在,当我尝试加载此特定网页时,文档 OuterHtml 为空,因此此测试失败

var url = "http://www.prettygreen.com/";
var htmlWeb = new HtmlWeb();
var htmlDoc = htmlWeb.Load(url);
var outerHtml = htmlDoc.DocumentNode.OuterHtml;
Assert.AreNotEqual("", pageHtml);

我可以毫无问题地从网站加载另一个页面,例如设置

url = "http://www.prettygreen.com/news/";

在过去,我曾经遇到过编码问题,我玩弄了 htmlWeb.OverrideEncoding 和 htmlWeb.AutoDetectEncoding,但没有成功。我不知道这个网页可能是什么问题。

【问题讨论】:

  • 尝试将您的 URL 字符串更改为:- @"http:\\www.prettygreen.com\";
  • 不走运,System.UriFormatException:无效 URI:无法解析主机名。

标签: c# html web-crawler html-agility-pack


【解决方案1】:

该网站似乎需要启用 cookie。因此,为您的 Web 请求创建一个 cookie 容器应该可以解决问题:

var url = "http://www.prettygreen.com/";
var htmlWeb = new HtmlWeb();
htmlWeb.PreRequest += request =>
    {
        request.CookieContainer = new System.Net.CookieContainer();
        return true;
    };
var htmlDoc = htmlWeb.Load(url);
var outerHtml = htmlDoc.DocumentNode.OuterHtml;
Assert.AreNotEqual("", outerHtml);

【讨论】:

  • 您将如何添加您已经从之前的HttpWebRequest 中获得的 cookie?
  • @MicroR:不能 100% 确定,但 cookie 应该在 htmlWeb 实例中可用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 2019-07-15
  • 1970-01-01
  • 2014-05-30
  • 2011-12-19
  • 2018-10-06
相关资源
最近更新 更多