Selenium+Python:Xpath定位祖先a标签并点击的问题求解
Hey there! Let's work through your two XPath problems and get that link clicked successfully.
1. Why text()="See Reviews" Fails but contains(text(),'See Reviews') Works
The issue here is almost certainly hidden whitespace in the <div> element's text. Even if the HTML looks clean like <div class="cj">See Reviews</div>, there might be invisible newlines, spaces, or tabs around the text that you can't see at a glance. The text() exact match checks for a perfect string (including any hidden whitespace), while contains() only cares that the target text exists somewhere in the string.
To fix the exact match, use normalize-space() to strip leading/trailing whitespace and collapse internal spaces:
# This will find the div even if there's hidden whitespace review_div = browser.find_element_by_xpath("//div[normalize-space(text())='See Reviews']")
2. Why Finding the Ancestor <a> Tag Failed (and a Better Approach)
Looking at your HTML, the <div> with "See Reviews" is a direct child of the <a> tag you want to click. Using ancestor::a isn't technically wrong, but it's overkill—parent::a is more precise and less likely to run into unexpected hierarchy issues.
That said, the most efficient way is to directly target the <a> tag instead of first finding the div. This cuts out an extra step and reduces the chance of errors:
# Directly locate the <a> tag that contains the target div browser.find_element_by_xpath("//a[div[normalize-space(text())='See Reviews']]").click()
Bonus: Avoid Element Loading Issues
If you're still getting NoSuchElementException, it might be because the element hasn't finished loading yet. Use WebDriverWait to ensure the element is ready to interact with:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By wait = WebDriverWait(browser, 10) # Wait up to 10 seconds review_link = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[div[normalize-space(text())='See Reviews']]"))) review_link.click()
内容的提问来源于stack exchange,提问作者PriyankaJ

