XPath,从HTML中的多个节点中选择多个元素

时间:2017-01-03 19:30:10

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

我无法想象这一个。

我必须搜索其中包含"item extend featured"个值的类的所有节点(下面的代码)。在这些类中,我需要选择其中<h2 class="itemtitle">href值的每个InnerText,以及<div class="title-additional">中的所有InnerTexts。

<li class="item extend featured">
    <div class="title-box">
        <h2 class="itemtitle">
            <a target="_top" href="www.example.com/example1/example2/exammple4/example4" title="PC Number 1">PC Number 1</a>
        </h2>
        <div class="title-additional">
            <div class="title-km">150 km</div>
            <div class="title-year">2009</div>
            <div class="title-price">250 €</div>
        </div>

输出应该是这样的:

Title:
href:
Title-km:
Title-year:
Title-Price:
--------------


Title:
href:
Title-km:
Title-year:
Title-Price:
--------------

那么,问题是,如何遍历html中的所有"item extend featured"节点并从每个节点选择上面需要的项目?

据我了解,这样的事情应该有效,但它会中途消失

编辑:我刚注意到,网站上有广告共享完全相同的类,他们显然没有我需要的元素。要考虑更多问题。

var items1 = htmlDoc.DocumentNode.SelectNodes("//*[@class='item extend featured']");

foreach (var e in items1)
{
   var test = e.SelectSingleNode(".//a[@target='_top']").InnerText;
   Console.WriteLine(test);
}

2 个答案:

答案 0 :(得分:1)

您要实现的目标需要多个XPath表达式,因为您可以使用一个查询在不同级别返回多个结果(除非您使用Union)。

您可能正在寻找的内容与此类似:

var listItems = htmlDoc.DocumentNode.SelectNodes("//li[@class='item extend featured']");

foreach(var li in listItems) {
    var title = li.SelectNodes("//h2/a/text()");
    var href = li.SelectNodes("//h2/a/@href");
    var title_km = li.SelectNodes("//div[@class='title-additional']/div[@class='title-km']/text()");
    var title_... // other divs
}

注意:未经过测试的代码

答案 1 :(得分:1)

var page = new HtmlDocument();
page.Load(path);
var lists = page.DocumentNode.SelectNodes("//li[@class='item extend featured']");
foreach(var list in lists)
{
    var link = list.SelectSingleNode(".//*[@class='itemtitle']/a");
    string title = link.GetAttributeValue("title", string.Empty);
    string href = link.GetAttributeValue("href", string.Empty);
    string km = list.SelectSingleNode(".//*[@class='title-km']").InnerText;
    string year = list.SelectSingleNode(".//*[@class='title-year']").InnerText;
    string price = list.SelectSingleNode(".//*[@class='title-price']").InnerText;
    Console.WriteLine("Title: %s\r\n href: %s\r\n Title-km: %s\r\n Title-year: %s\r\n Title-Price: %s\r\n\r\n", title, href, km, year, price);
}