【问题标题】:c# htmlagility pack conditional select node时间:2019-04-10 标签:c#htmlagilitypack条件选择节点
【发布时间】:2016-06-19 16:07:11
【问题描述】:

我不确定标题是否适合我的问题。 我有如下 html

<table id="searchResultsTable" class="">

<tbody>
    <tr class="searchResultsItem even     ">
            <td class="searchResultsPriceValue">
            <div> 26.500 TL</div></td>
        <td class="searchResultsTitleValue ">
                    <a class="classifiedTitle" href="xxxx"> some text</a>
    </tr>
    <tr class="searchResultsItem odd     ">
    .
    //same as "searchResultsItem even     "
    .
    </tr>   

</tbody>

</table>

我是 htmlagility 包的新手。我已经成功获得了“searchResultsItem even”和“searchResultsItemodd”的价格值。

如果价格低于或高于某个值,我想获得 href 值。我可以得到href,但一直都是“searchResultsItem”。如果偶数的价格值符合我的偶数条件并且奇数符合我想要的奇数条件,我想获得 href。

下面是我的代码

foreach (HtmlNode node1 in doc.DocumentNode.SelectNodes("//table[@id='searchResultsTable']"))
                {
                    foreach (HtmlNode node2 in node.SelectNodes("//td[@class='searchResultsPriceValue']"))
                    {
                        string price = node2.InnerText.ToString();
                        price = price.Trim().Replace(".", String.Empty);
                        price = price.Replace("TL", String.Empty);
                        if (Convert.ToInt32(price) < 28000)
                        {
                            HtmlNode node3 = node.SelectSingle(".//a[@class='classifiedTitle']");
                            listBox1.Items.Add(node3.Attributes["href"].Value);
                        }
                    }
                }

谢谢

【问题讨论】:

    标签: c# html-agility-pack


    【解决方案1】:

    获取tr 类名作为属性值。先循环遍历行,然后循环tds。

    foreach (HtmlNode node1 in doc.DocumentNode.SelectNodes("//table[@id='searchResultsTable']"))
    {
      foreach (HtmlNode tr in table.SelectNodes("//tr"))
      {
        var @class = tr.GetAttributeValue("class", string.Empty);
        switch (@class) {
              // rest of your parsing
        }
      }
    }
    

    【讨论】:

    • 抱歉,我不知道 GetAttributeValue 是如何工作的。我运行你的代码,但@class 变量总是空的
    猜你喜欢
    • 2017-01-09
    • 2016-04-19
    • 2022-01-16
    • 2018-07-04
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 2015-02-10
    相关资源
    最近更新 更多