我想从这个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();
}发布于 2014-03-21 22:49:35
您需要使用HtmlAgilityPack的GetAttributeValue方法获取锚固元件的值。您可以通过直接提取父块代码元素的内容来访问单个锚元素,如下所示:
//div@id='first-tweet-wrapper'/blockquote@class='twitter-tweet‘
然后取出内部的单个链接。一个可能的解决方案可能是这样的(在这种情况下,输入是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);
}在本例中,输出如下:
另一种可能是使用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);
}输出与上面相同。
发布于 2014-03-21 23:25:34
假设您的<div> id是"first-tweet-wrapper“而不是"firt",您可以使用这个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", "");
}https://stackoverflow.com/questions/22570705
复制相似问题