如何使用XPath获得此功能

时间:2013-07-18 11:26:09

标签: c# xpath

我正在为其中一个网站编写一个Crawler,并且遇到了这个问题。

从这个HTML ...

<div class="Price">
    <span style="font-size: 14px; text-decoration: line-through; color: #444;">195.90 USD</span>
    <br />
    131.90 USD           
</div>

我需要使用XPath才能获得 131.90 USD

试过这个......

"//div[@class='Price']"

但它会返回不同的结果。

我怎样才能做到这一点?

修改

我正在使用这个C#代码(简化为演示)

protected override DealDictionary GrabData(HtmlAgilityPack.HtmlDocument html) {
var price = Helper.GetInnerHtml(html.DocumentNode, "//div[@class='Price']/text()");

}

助手类

public static class Helper {
    public static String GetInnerText(HtmlDocument doc, String xpath) {
        var nodes = doc.DocumentNode.SelectNodes(xpath);
        if (nodes != null && nodes.Count > 0) {
            var node = nodes[0];
            return node.InnerText.TrimHtml();
        }
        return String.Empty;
    }

    public static String GetInnerText(HtmlNode inputNode, String xpath) {
        var nodes = inputNode.SelectNodes(xpath);
        if (nodes != null && nodes.Count > 0) {
            var node = nodes[0];
            var comments = node.ChildNodes.OfType<HtmlCommentNode>().ToList();
            foreach (var comment in comments)
                comment.ParentNode.RemoveChild(comment);

            return node.InnerText.TrimHtml();
        }
        return String.Empty;
    }

    public static String GetInnerHtml(HtmlDocument doc, String xpath) {
        var nodes = doc.DocumentNode.SelectNodes(xpath);
        if (nodes != null && nodes.Count > 0) {
            var node = nodes[0];
            return node.InnerHtml.TrimHtml();
        }
        return String.Empty;
    }

    public static string GetInnerHtml(HtmlNode inputNode, string xpath) {
        var nodes = inputNode.SelectNodes(xpath);
        if (nodes != null && nodes.Count > 0) {
            var node = nodes[0];
            return node.InnerHtml.TrimHtml();
        }
        return string.Empty;
    }
}

1 个答案:

答案 0 :(得分:1)

你尝试的XPath是一个好的开始:

//div[@class='Price']

这将选择Xml文档中的任何<div>元素。您可以将该选择限制为<div>元素,其class属性的值为Price

到目前为止,非常好 - 但是当您选择<div>元素时,您将获得的内容将是<div>元素,包括其所有内容。

在上面显示的Xml片段中,您有以下层次结构:

<div> element
    <span> element
        text node
    <br> element
    text node

所以,你真正感兴趣的是后一个文本节点。您可以在XPath中使用text()来选择任何文本节点。在这种情况下,您感兴趣的是第一个文本节点,它是您找到的<div>元素的直接子节点,您的XPath应如下所示:

//div[@class='Price']/text()