C# html agility pack get elements by class name

前端 未结 5 904
忘了有多久
忘了有多久 2021-01-04 05:33

I\'m trying to get all the divs that their class contains a certain word:

content1
相关标签:
5条回答
  • 2021-01-04 05:43

    I got it:

    resultContent.DocumentNode.SelectNodes("//div[contains(@class, 'hello')]"))
    
    0 讨论(0)
  • 2021-01-04 05:51

    as you have specified that the class has to contain a certain word, the following will ensure that the word is:

    • at the start of the string and followed by a space
    • or in the middle of the string and surrounded by whitespace
    • or at the end of the string and preceded by a space
    • or the only class name in the class attribute

    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 ')]");
    
    0 讨论(0)
  • 2021-01-04 06:00
    HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
    htmlDoc.Load(filePath);
     foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//div[@class='hello']")
     {
        //code
     }
    
    0 讨论(0)
  • 2021-01-04 06:02

    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"));
    
    0 讨论(0)
  • 2021-01-04 06:02

    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"));
    
    0 讨论(0)
提交回复
热议问题