나는이 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();
}
HtmlAgilityPack의 GetAttributeValue 메소드를 사용하여 앵커 요소 의 href 속성 값 을 가져와야합니다. 다음과 같이 부모 블록 코드 요소의 내용을 직접 추출하여 단일 앵커 요소에 액세스 할 수 있습니다.
// div [@ id = 'first-tweet-wrapper'] / blockquote [@ class = 'twitter-tweet']
그런 다음 내부에 단일 링크를 가져옵니다. 가능한 솔루션은 다음과 같습니다 (이 경우 입력은 페이스 북 이지만 마이크로 소프트 에서도 작동합니다).
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 suggest).
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가 "firt"대신 "first-tweet-wrapper"라고 가정하면이 XPath 쿼리를 사용하여 <a>
요소를 <blockquote>
안에 넣을 수 있습니다.
//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", "");
}