【问题标题】:Xpath:How to get data from div tagXpath:如何从 div 标签中获取数据
【发布时间】:2014-06-28 11:16:55
【问题描述】:
<div id="caption">
<div>
    Position: Passenger Side Front
    <br></br>
    Color: Black
    <br></br>
    Finish: Smooth / Paintable
    <br></br>
    Part Brand: LatchWell
    <br></br>
    Lifetime Warranty
</div>

我需要 xpath 来获取 Part Brand : 值。我想要的 OP 是
LatchWell

这是我的代码:

  tag = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='caption']//div");
            if (tag != null)
            {
                wi.Brand = tag.InnerText.Trim();
            }

我无法使用拆分函数进行拆分,因为 Part Brand 上方和下方的数据是动态的。

【问题讨论】:

    标签: c# xpath web-scraping html-agility-pack


    【解决方案1】:

    由于除了两个 &lt;div&gt; 标记之外,您有一个 HTML 标记无法使用 HtmlAgilityPack 选择,因此您必须使用某种其他方法,例如正则表达式评估。

    假设Part Brand: something &lt;br&gt;&lt;br&gt; 始终存在于您的代码中,您可以选择Part Brand:&lt;br&gt; 之间的文本并获取品牌名称。

    HtmlNode brandNode = doc.DocumentNode.SelectSingleNode("//div[@id='caption']//div");
    string brand = Regex.Match(brandNode.InnerHtml, "Part Brand: (.*?)<br>").Groups[1].Value;
    Console.WriteLine(brand);
    

    Regex.Match(string, regexp) 这个简单的使用将输出Latchwell

    【讨论】:

      【解决方案2】:

      实际上,您可以使用 XPath 选择特定的 HTML 行,例如:

      var tag = htmlDoc.DocumentNode
                       .SelectSingleNode("//div[@id='caption']/div/text()[contains(.,'Part Brand:')]");
      //given html input as posted in this question, following will print : "LatchWell"
      Console.WriteLine(tag.InnerText.Trim().Replace("Part Brand: ", ""));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-23
        • 1970-01-01
        相关资源
        最近更新 更多