获取<a href="https://www.google.se/"> adress width html agility pack</a>

时间:2014-05-23 13:26:31

标签: c# html-agility-pack

我有这个HTML:

<div class="table-wrapper" style='display: block;'>
<table id="tableSearchArticle">
    <thead>
        <tr>
            <th><a href="#">Article</a></th>
            <th><a href="#">art.nr.</a></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <a href="http://www.dabas.com/ProductSheet/Detail.ashx/121308" target="_blank">
                    Apple
                </a>
            </td>
            <td><span class="mobile-only">Tillverkarens art.nr:</span>11068</td>
        </tr>
        <tr>
            <td>
                <a href="http://www.dabas.com/ProductSheet/Detail.ashx/124494" target="_blank">
                   Banana
                </a>
            </td>
            <td><span class="mobile-only">Tillverkarens art.nr:</span>11405</td>
        </tr>
    </tbody>
</table>

这是我的方法,应该得到表中的所有href地址。但是现在我只得到一个文章名称列表。我的清单归还Apple,Banana。我想返回一个href-http-adresses列表。我怎么能这样做?

        public List<string> GetListOfHrefs()
    {
        HtmlWeb web = new HtmlWeb();
        HtmlDocument doc = web.Load("http://www.dabas.com/mypages/search.aspx?typ=FP&sosokord=laggen");
        var xpath = "//table[@id='tableSearchArticle']/tbody/tr/td[1]//@href";
        var listOfGtins = doc.DocumentNode.SelectNodes(xpath)
            .Select(td => td.InnerText.Replace("GTIN:", "")).ToList();
        return listOfGtins;
    }

1 个答案:

答案 0 :(得分:2)

XPath中的两个问题 - hrefa元素的属性,而不是td元素的属性,并且您无法使用XPath选择属性 - 您应该选择元素:

var xpath = "//table[@id='tableSearchArticle']/tbody/tr/td/a[@href]";
var links = doc.DocumentNode.SelectNodes(xpath)
               .Select(a => a.Attributes["href"].Value);

输出:

[
  "http://www.dabas.com/ProductSheet/Detail.ashx/121308",
  "http://www.dabas.com/ProductSheet/Detail.ashx/124494"
]