1

Trying to get the XPath of div class and the text inside of the div. the two divs are:

<div class="product-card__subtitle">Women's Shoe</div>
<div class="product-card__subtitle">Men's Shoe</div>

My Xpaths that are giving the selenium error are:

driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text("
                                                      ")='Women's Shoe']")

driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()='Men's "
                                                    "Shoe']")

I am trying to get the path for the part that says "Women's shoe" and another path for the part that says "Men's shoe" pic

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
kj123
  • 41
  • 8

2 Answers2

1

The root cause is the text has symbol '.
Although you can optimize other xpath syntax expression, you don't have to.

EDIT 1:

driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()=\"Women's Shoe\"]")

driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()=\"Men's Shoe\"]")

I thought the below is right, but when verifying in chrome console, I still got error "not a valid XPath expression"

driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()='Women\'s Shoe']")

driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()='Men\'s Shoe']")
Peter Quan
  • 788
  • 4
  • 9
  • I am getting this error ```selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //div[contains(@class, 'product-card__subtitle') and text()='Men's Shoe'] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[contains(@class, 'product-card__subtitle') and text()='Men's Shoe']' is not a valid XPath expression. (Session info: chrome=84.0.4147.125)``` – kj123 Aug 15 '20 at 17:32
  • Yes, sorry. The original answer still has syntax error, I will fix it. In fact, I think a shorter xpath should work fine, just try `"//div[text()=\"Men's Shoe\"]"` – Peter Quan Aug 16 '20 at 02:31
1

This error message...

SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[contains(@class, 'product-card__subtitle')

...implies that the XPath which you have used was not a valid XPath expression.


Solution

To locate the desired elements you can use the following based Locator Strategies:

  • Women's Shoe:

    driver.find_element_by_xpath("//div[@class='product-card__subtitle' and contains(., \"Women's Shoe\")]")
    
  • Men's Shoe:

    driver.find_element_by_xpath("//div[@class='product-card__subtitle' and  contains(., \"Men's Shoe\")]")
    

References

You can find a couple of relevant detailed discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352