使用Selenium通过已知title属性定位获取上层tr元素的id值
实现方案
方案1:直接通过XPath一步定位到目标tr
你可以通过XPath的祖先轴直接定位到对应a标签上层的tr元素,无需先单独获取a标签对象:
# 定位到指定title属性的a标签的最近上层tr tr_ele = driver.find_element_by_xpath("//a[starts-with(@title, 'title that I have obtained')]/ancestor::tr[1]") # 读取tr的id属性值 tr_id = tr_ele.get_attribute("id")
其中ancestor::tr[1]的作用是匹配当前节点的所有祖先节点中,距离最近的1个tr标签,完全适配你给出的HTML结构。
方案2:基于已获取的a标签元素向上查找
如果你已经提前拿到了a标签的WebElement对象,可以直接基于该对象做向上层级查找:
# 你已获取的a标签元素 a_ele = driver.find_element_by_css_selector("[title^='title that I have obtained']") # 从a元素出发查找最近的上层tr tr_ele = a_ele.find_element_by_xpath("./ancestor::tr[1]") tr_id = tr_ele.get_attribute("id")
如果你使用Selenium 4及以上版本,原
find_element_by_*系列方法已被弃用,推荐使用标准By类写法避免告警:from selenium.webdriver.common.by import By # 对应方案1的Selenium 4写法 tr_ele = driver.find_element(By.XPATH, "//a[starts-with(@title, 'title that I have obtained')]/ancestor::tr[1]") tr_id = tr_ele.get_attribute("id")
内容的提问来源于stack exchange,提问作者Diego Ruiz
相关产品推荐
相关产品推荐

