Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find an element by CSS class with XPath?

Tags:

html

css

xml

xpath

In my webpage, there's a div with a class named Test.

How can I find it with XPath?

like image 350
Strawberry Avatar asked Oct 22 '09 00:10

Strawberry


People also ask

How do you find the nth element using XPath and css?

By adding square brackets with index. By using position () method in xpath.

How do you find the XPath of a class?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

Can we use class for XPath?

To identify the element with css, the expression should be tagname[class='value'] and the method to be used is By. cssSelector. To identify the element with xpath, the expression should be //tagname[@class='value']. Then, we have to use the method By.


2 Answers

This selector should work but will be more efficient if you replace it with your suited markup:

//*[contains(@class, 'Test')] 

Or, since we know the sought element is a div:

//div[contains(@class, 'Test')] 

But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak's version provided in the comments is better:

//div[contains(concat(' ', @class, ' '), ' Test ')] 

If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):

//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')] 

Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.

like image 174
meder omuraliev Avatar answered Sep 26 '22 15:09

meder omuraliev


Most easy way..

//div[@class="Test"] 

Assuming you want to find <div class="Test"> as described.

like image 33
Olli Puljula Avatar answered Sep 26 '22 15:09

Olli Puljula