获取DIV内的链接

我希望能够从这个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(); } 

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

// DIV [@ ID = ‘第一鸣叫-包装’] / BLOCKQUOTE [@类= ‘Twitter的鸣叫’]

然后获取里面的单个链接。 一个可能的解决方案可能看起来像这样(在这种情况下,输入是Facebook ,但也适用于微软 ):

 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); } 

输出与上面相同。

假设你的

id是“first-tweet-wrapper”而不是“firt”,你可以使用这个XPath查询来获取

元素:

 //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", ""); }