获取DIV内的链接

本文关键字:链接 DIV 获取 | 更新日期: 2023-09-27 17:51:19

我希望能够从这个div中获得第一个链接。

    <div id="first-tweet-wrapper">
    <blockquote class="tweet" lang="en">
    <a href="htttp://link.com">                          <--- This one
      text    </a>
  </blockquote>
  <a href="http://link2.net" class="click-tracking" target="_blank"
     data-tracking-category="discover" data-tracking-action="tweet-the-tweet">
    Tweet it!  </a>
</div>

我试过这段代码,但它不起作用

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(source);
var div = doc.DocumentNode.SelectSingleNode("//div[@id='first-tweet-wrapper']");
if (div != null)
{
      var links = div.Descendants("a")
          .Select(a => a.InnerText)
          .ToList();
}

获取DIV内的链接

您需要使用htmllagilitypack的GetAttributeValue方法获取锚元素的href-attribute。您可以通过直接提取父块代码元素的内容来访问单个锚元素,如下所示:

//div [@ id = ' first-tweet-wrapper ']/blockquote [@class = '推文文']

然后获取里面的单个链接。一个可能的解决方案可能是这样的(在本例中,输入是facebook,但也适用于microsoft):

try
{           
    // download the html source
    var webClient = new WebClient();
    var source = webClient.DownloadString(@"https://discover.twitter.com/first-tweet?username=facebook#facebook");
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(source);
    var div = doc.DocumentNode.SelectSingleNode("//div[@id='first-tweet-wrapper']/blockquote[@class='twitter-tweet']");
    if (div != null)
    {
        // there is only one links
        var link = div.Descendants("a").FirstOrDefault();
        if (link != null)
        {
            // take the value of the attribute
            var href = link.GetAttributeValue("href", "");
            Console.WriteLine(href);
        }
    }
}
catch (Exception exception)
{
    Console.WriteLine(exception.Message);
}

在本例中输出为:

https://twitter.com/facebook/statuses/936094700

另一种可能是使用XPath直接选择锚元素(如建议的@har07):

    var xpath = @"//div[@id='first-tweet-wrapper']/blockquote[@class='twitter-tweet']/a";
    var link = doc.DocumentNode.SelectSingleNode(xpath);
    if (link != null)
    {
        // take the value of the href-attribute
        var href = link.GetAttributeValue("href", "");
        Console.WriteLine(href);
    }

输出和上面一样

假设您的<div> id是"first-tweet-wrapper"而不是"first ",您可以使用此XPath查询在<blockquote>中获取<a>元素:

//div[@id='first-tweet-wrapper']/blockquote/a
所以你的代码看起来像这样:
var a = doc.DocumentNode
             .SelectSingleNode("//div[@id='first-tweet-wrapper']/blockquote/a");
if (a != null)
{
      var text = a.InnerText;
      var link = a.GetAttributeValue("href", "");
}