XPath to match @class value and element value?
Solution 1
This XPath expression:
//div[contains(@class, 'item-price') and contains(., '$')]
Will match all div
elements of the item-price
class containing a '$'.
It's useful to use contains()
in the test on @class
if you want to match cases where there are multiple CSS styles specified in the @class
value.
Caution: For a more robust solution, apply the following technique to avoid unintended substring matches (item-price
matching, say, item-prices
):
//div[contains(concat(' ',@class,' '), ' item-price ') and contains(., '$')]
Solution 2
//div[@class = 'item-price'][contains(., '$')]
Solution 3
As per the HTML:
<div class="item-price">$0.99</div>
There is:
- Only one value of the class attribute i.e.
item-price
- And the innerText starts with a
$
sign.
So, to locate this element with respect to the value of the class attribute i.e. item-price
and innerText content starting with a dollar sign ($
) you can use either of the following solutions:
Using
starts-with()
://div[@class='item-price' and starts-with(., '$')]
Using
contains()
://div[@class='item-price' and contains(., '$')]
Terrence Brannon
The essence of software design is abstraction. Python is good, but I yearn for the strong-typing of Haskell?
Updated on August 22, 2020Comments
-
Terrence Brannon over 3 years
I would like to locate this element,
<div class="item-price">$0.99</div>
using XPath which says select
div
elements whoseclass
attribute equals"item-price"
and whose content contains a dollar sign ($
). -
Terrence Brannon over 10 yearsI like the telepathic support you are giving me by telling me about
contains()
because it is very valuable. I like the conjunctive syntax used above a bit more. So I'm torn on which to select as the answer because both are correct. -
kjhughes almost 6 yearsYou're welcome for the telepathic support. After nearly 5 years, perhaps you're now able to select one answer or the other to accept now? :-)