How to get html elements with multiple css classes

Html Agility-Pack

Html Agility-Pack Problem Overview


I know how to get a list of DIVs of the same css class e.g

<div class="class1">1</div>
<div class="class1">2</div>

using xpath //div[@class='class1']

But how if a div have multiple classes, e.g

<div class="class1 class2">1</div>

What will the xpath like then?

Html Agility-Pack Solutions


Solution 1 - Html Agility-Pack

The expression you're looking for is:

//div[contains(@class, 'class1') and contains(@class, 'class2')]

I highly suggest XPath visualizer, which can help you debug xpath expressions easily. It can be found here:

http://xpathvisualizer.codeplex.com/

Solution 2 - Html Agility-Pack

According to this answer, which explains why it is important to make sure substrings of the class name that one is looking for are not included, the correct answer should be:

//div[contains(concat(' ', normalize-space(@class), ' '), ' class1 ')
    and contains(concat(' ', normalize-space(@class), ' '), ' class2 ')]

Solution 3 - Html Agility-Pack

There's a useful python package called cssselect.

from cssselect import CSSSelector CSSSelector('div.gallery').path

Generates a usable XPath:

descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' gallery ')]

It's very similar to Flynn1179's answer.

Solution 4 - Html Agility-Pack

i think this the expression you're looking for is

//div[starts-with(@class, "class1")]/text()

Solution 5 - Html Agility-Pack

You could also do:

//div[contains-token(@class, 'class_one') and contains-token(@class, 'class_two')]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionseasongView Question on Stackoverflow
Solution 1 - Html Agility-PackIoannis KaradimasView Answer on Stackoverflow
Solution 2 - Html Agility-PackVic SeedoubleyewView Answer on Stackoverflow
Solution 3 - Html Agility-PacksteveayreView Answer on Stackoverflow
Solution 4 - Html Agility-Packrishi singhView Answer on Stackoverflow
Solution 5 - Html Agility-PackHelpNeederView Answer on Stackoverflow