I\'m trying to get all the divs that their class contains a certain word:
content1
I got it:
resultContent.DocumentNode.SelectNodes("//div[contains(@class, 'hello')]"))
as you have specified that the class has to contain a certain word, the following will ensure that the word is:
It does so by comparing the value of the class attribute surrounded by spaces with the specified word (hello
) surrounded by spaces. This is to avoid false positives like class="something-hello-something"
resultContent.DocumentNode.SelectNodes("//div[contains(concat(' ', @class, ' '), ' hello ')]");
HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.Load(filePath);
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//div[@class='hello']")
{
//code
}
As of version v1.6.5 of Html Agility Pack, it contains .HasClass("class-name")
extension method.
IEnumerable<HtmlNode> nodes =
htmlDoc.DocumentNode.Descendants(0)
.Where(n => n.HasClass("class-name"));
I'm sure because there're multiple classes in your div, that doesn't work. You can try this instead:
resultContent.DocumentNode.Descendants("div").Where(d => d.Attributes["class"].Value.Contains("hello"));