seasong
seasong

Reputation: 803

How to get html elements with multiple css classes

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?

Upvotes: 70

Views: 76044

Answers (5)

Ioannis Karadimas
Ioannis Karadimas

Reputation: 7896

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.

Upvotes: 147

HelpNeeder
HelpNeeder

Reputation: 6480

You could also do:

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

Upvotes: 0

Vic Seedoubleyew
Vic Seedoubleyew

Reputation: 10526

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

Upvotes: 7

steveayre
steveayre

Reputation: 1083

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.

Upvotes: 2

rishi singh
rishi singh

Reputation: 19

i think this the expression you're looking for is

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

Upvotes: 1

Related Questions