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

蹲街弑〆低调 提交于 2021-02-04 08:10:56

问题


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"


回答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 xpath 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:

  • SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//img[contains('1236548597')]' is not a valid XPath expression
  • selenium - Failed to execute 'evaluate' on 'Document': The string is not a valid XPath expression



回答2:


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']")


来源:https://stackoverflow.com/questions/63422288/python-selenium-syntaxerror-failed-to-execute-evaluate-on-document-the-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!