I'm looping through some <li>
tags and within this tag there is an <a>
tag of class="track-visit-website"
:
<li><a class="track-visit-website" href="abc1">Anchor1</a></li>
I want to grab the href of <a>
tags. But in some <li>
there is no <a>
tags so my code is throwing error.
My Code is :
List<string> Website = new List<string>();
HtmlDocument hoteleWebsiteDoc = new HtmlDocument();
hoteleWebsiteDoc.LoadHtml(hotels.InnerHtml);
var hotelWebsite = from lnks in hoteleWebsiteDoc.DocumentNode.Descendants()
where lnks.Name == "a" && lnks.Attributes.Contains("class") &&
lnks.Attributes["class"] != null &&
lnks.Attributes["class"].Value.Contains("track-visit-website") &&
lnks.InnerText.Trim().Length > 0
select new
{
Url = lnks.Attributes["href"].Value,
};
foreach (var website in hotelWebsite)
{
if (!string.IsNullOrEmpty(website.Url) || !string.IsNullOrWhiteSpace(website.Url))
Website.Add(website.Url.Trim());
else
Website.Add(" ");
}
What should I do ? I thought of checking first whether the tag exists or not and then execute the code. But how can i check whether the tag exists or not? Or is there some other way ?
var items = hoteleWebsiteDoc
.DocumentNode.SelectNodes("//li/a[@class='track-visit-website']");
if(items!=null)
{
var links = items.Select(a => a.Attributes["href"].Value).ToList();
}
This solution take into account the possible case in which the a
tag not contains the href
attribute, for example :
<li>
<a class='track-visit-website' href='abc1'>Anchor1</a>
</li>
<li>
<a class='track-visit-website'>Anchor 2</a>
</li>
<li>
</li>
var hoteleWebsiteDoc = (from element in doc.DocumentNode.Descendants("a")
where element.ParentNode.Name.Equals("li") &&
element.Attributes.Contains("class") &&
element.Attributes.Contains("href") &&
element.Attributes["class"].Value.Equals("track-visit-website")
select new
{
URL = element.Attributes["href"].Value
}).ToList();
foreach (var obj in hrefsList)
{
Console.WriteLine(obj.URL);
}
Or if you want to keep the other solution instead you can change your code for this to check if contains the href
attribute :
if (items != null)
{
var links = items.Where(a => a.Attributes.Contains("href")).Select(a => a.Attributes["href"].Value).ToList();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.