问题
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