Selenium如何定位h1.important之后首个class为b的元素
问题解决方法
你之前的写法会匹配页面内所有.b类元素,默认取第一个自然会拿到不符合要求的内容,以下是可用的定位方案:
1. XPath 方案(推荐,兼容性更强)
XPath的following轴可以直接匹配指定节点之后所有层级的元素,定位写法为://h1[contains(@class,"important")]/following::div[contains(@class,"b")][1]
用contains匹配class是为了避免元素有多个class时匹配失效,如果确定class只有important和b也可以直接用@class="important"。
Selenium 调用示例
# Selenium 4.x 版本 from selenium.webdriver.common.by import By target_text = driver.find_element(By.XPATH, '//h1[@class="important"]/following::div[@class="b"][1]').text # Selenium 3.x 及更早版本 target_text = driver.find_element_by_xpath('//h1[@class="important"]/following::div[@class="b"][1]').text
2. CSS 选择器方案
CSS没有向前/任意后续节点匹配的能力,需要依赖你给出的HTML结构层级来写,写法为:.title ~ .a .b~是后续兄弟选择器,会匹配.title节点之后所有同级的.a节点,再取其子节点中的.b元素,Selenium取第一个匹配项即可。
Selenium 调用示例
# Selenium 4.x 版本 from selenium.webdriver.common.by import By target_text = driver.find_element(By.CSS_SELECTOR, '.title ~ .a .b').text # Selenium 3.x 及更早版本 target_text = driver.find_element_by_css_selector('.title ~ .a .b').text
内容的提问来源于stack exchange,提问作者Noniq
相关产品推荐
相关产品推荐

