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

2018-12-31 15:33发布

问题:

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

How can I find it with XPath?

回答1:

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.



回答2:

Most easy way..

//div[@class=\"Test\"]

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



回答3:

I\'m just providing this as an answer, as Tomalak provided as a comment to meder\'s answer a long time ago

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


回答4:

The ONLY right way to do it with XPath :

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

The function normalize-space strips leading and trailing whitespace, and also replaces sequences of whitespace characters by a single space.


Note

If not need many of these Xpath queries, you might want to use a library that converts CSS selectors to XPath, as CSS selectors are usually a lot easier to both read and write than XPath queries. For example, in this case, you could use both div[class~=\"foo\"] and div.foo to get the same result.

Some libraries I\'ve been able to find :

  • For JavaScript : css2xpath & css-to-xpath
  • For PHP : CssSelector Component
  • For Python : cssselect
  • For C# : css2xpath Reloaded
  • For GO : css2xpath


回答5:

An helpful function can be made out of previous answers:

function matchClass($className) {
    return \"[contains(concat(\' \', normalize-space(@class), \' \'), \' $className \')]\";
}

Then just concat the function call into your query.



回答6:

you can find elements like this example (all css elements)

private By 
allElementsCss = By.xpath(\".//div[@class]\");


标签: html css xml xpath