【问题标题】:Xpath returning null with html agility packXpath 使用 html 敏捷包返回 null
【发布时间】:2012-07-18 11:43:19
【问题描述】:

我正在使用 Html Agility Pack 来获取页面上每个产品的信息:

我的代码是这样,但节点返回 null。我正在使用通过 Google Chrome 找到的 Xpath。

private void getDataBtn_Click(object sender, EventArgs e)
    {
        if (URL != null)
        {
            HttpWebRequest request;
            HttpWebResponse response;
            StreamReader sr;

            List<string> Items = new List<string>(50);
            HtmlAgilityPack.HtmlDocument Doc = new HtmlAgilityPack.HtmlDocument();

            request = (HttpWebRequest)WebRequest.Create(URL);
            response = (HttpWebResponse)request.GetResponse();
            sr = new StreamReader(response.GetResponseStream());

            Doc.Load(sr);

            var Name = Doc.DocumentNode.SelectSingleNode("/html/body/table[2]/tbody/tr/td[2]/table/tbody/tr[2]/td/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[3]/a");
        }
    }

我做错了什么?有没有其他工具可以创建兼容敏捷包的 xpath 表达式?

【问题讨论】:

  • 我明白你的意思...问题是网页会动态加载一些内容。当您尝试获取未加载动态内容的页面时,这就是您获得空值的原因..请参阅我的问题..有同样的问题。 stackoverflow.com/questions/18955793/…

标签: c# html parsing xpath html-agility-pack


【解决方案1】:

因为这个页面没有这个节点。当您通过敏捷包(而不是浏览器)下载它时,页面有以下文本:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HobbyKing Page not found.</title>
</head>

<body>
<img src="http://www.hobbyking.com/hk_logo.gif"><br>
<span style="font-family:Verdana, Arial, Helvetica, sans-serif">
<strong>Page no longer available</strong><br>
It seems you have landed on a page that doesnt exist anymore.<br>
Please update your links to point towards the correct hobbyking.com location;<br>
<a href="http://www.hobbyking.com/hobbyking/store/uh_index.asp">http://www.hobbyking.com/hobbyking/store/uh_index.asp</a><br>
<br>
If you continue to see this message, please email <a href="mailto:support@hobbyking.zendesk.com">support@hobbyking.zendesk.com</a></span>
</body>
</html>

您可以在页面中看到以下句子:
"请更新您的链接以指向正确的 hobbyking.com 位置;
http://www.hobbyking.com/hobbyking/store/uh_index.asp"

附言您可以通过在visual-studio的调试中检查它来查看它。

【讨论】:

  • 那么你应该使用 HttpResponse 和 Request 来获取源代码。顺便说一句,在这之后一切都将变为 null /html/body/table[2]
猜你喜欢
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
  • 2014-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
相关资源
最近更新 更多