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

前端 未结 6 1335
刺人心
刺人心 2020-11-22 08:43

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

How can I find it with XPath?

6条回答
  •  梦如初夏
    2020-11-22 09:05

    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~="Test"] and div.Test 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

提交回复
热议问题