70

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?

1
  • 1
    Maybe it would be better to use CSS paths Commented Jan 15, 2018 at 15:46

5 Answers 5

148

The expression you're looking for is:

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

There are multiple XPath visualisation tools online that can greatly help test any expression.

Sign up to request clarification or add additional context in comments.

4 Comments

Minor problem with this solution is that it'll potentially break if a possible class name is a substring of another. For example, if you also have 'class11', it'll erroneously match this, as it contains 'class1'. This is very easy to avoid though, just make sure class names don't contain each other.
Agreed, but given what 's being discussed here involves scanning an attribute's string value, in XPath speak, I 'm not sure if it can be avoided.
Well, if it was really necessary you could do contains(concat(' ', @class, ' '), ' class1 ') etc., but as I said, it's very easy to avoid the need for that.
This did it for me! Took me forever to solve this!
7

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 ')]

Comments

2

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.

Comments

1

i think this the expression you're looking for is

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

Comments

0

You could also do:

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

1 Comment

This doesn't work here. Is contains-token an official functionality?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.