You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:24:03