【问题标题】:Get value between html tags Xpath and HtmlAgility获取 html 标签 Xpath 和 HtmlAgility 之间的值
【发布时间】:2013-10-14 10:34:08
【问题描述】:

到目前为止,我正在尝试检索某个网站的 HTML 标记之间的文本....

例如,我需要提取这些跨度标签之间的文本,我将如何处理,我收到一条错误消息,指出“对象引用未设置为对象的实例”这里是 HTML

这部分之前还有 HTML 代码;我不知道这是否应该有所作为。

<div class="thumbnail-details">
<ul>
    <li> … </li>
    <li class="product-title">
        <span class="thumbnail-details-grey">The Blaster Portable Wireless Speaker in Black</span>
    </li>
    <li> … </li>
</ul>
</div>

到目前为止,我的 C# 代码是

    HtmlWeb hw = new HtmlWeb();
        HtmlAgilityPack.HtmlDocument htmlDoc = hw.Load(@"http://www.karmaloop.com/Browse.htm#Pgroup=1");
        if (htmlDoc.DocumentNode != null)
        {
            foreach (HtmlNode text in htmlDoc.DocumentNode.SelectNodes("//span[@class='thumbnail-details-grey']/text()"))
            {
                Console.WriteLine(text.InnerText);
            }

我能在这里得到一些帮助吗,我想提取“The Blaster Portable Wireless Speaker in Black”。

【问题讨论】:

  • 你在哪里得到错误?我猜它在 if 语句中并且 htmlDoc 为空。如果我是对的,您可以将 if 语句更改为 if (htmlDoc != null &amp;&amp; htmlDoc.DocumentNode != null) 以消除该错误,但随后需要找出它未加载的原因。

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


【解决方案1】:

我建议使用 CsQuery (https://www.nuget.org/packages/CsQuery/1.3.4),然后它就这么简单:

var doc = CQ.CreateFromUrl(@"http://www.karmaloop.com/Browse.htm");
var nodes = doc.Find("span.thumbnail-details-grey");
foreach(var node in nodes)
    Console.WriteLine(node.InnerText);

【讨论】:

  • 这里看起来很有趣,将不得不研究 CsQuery。谢谢
【解决方案2】:

您的代码运行良好,但您必须加载正确的页面才能使其运行。您正在加载的页面使用 ajax 请求来加载您在浏览器中看到的结果。

因此,您必须使用以下网址,而不是您当前使用的网址:

HtmlDocument htmlDoc = hw.Load(@"http://www.karmaloop.com/Browse?Pgroup=1&ajax=true&version=2");

然后你的代码就可以工作了。我仍在寻找将这个请求放在一起的地方......

但查询看起来很容易猜到。例如页面http://www.karmaloop.com/Browse.htm#Pdept=11&amp;PageSize=30&amp;Pgroup=1请求urlhttp://www.karmaloop.com/Browse?Pdept=11&amp;PageSize=30&amp;Pgroup=1&amp;ajax=true&amp;version=2。因此,您所要做的就是使用您的网址并在# 之后开始构建一个新网址。

【讨论】:

  • 感谢您的解决方案。现在按需要工作,感谢它。
猜你喜欢
  • 2021-03-31
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 2012-02-15
  • 1970-01-01
相关资源
最近更新 更多