You need to enable JavaScript to run this app. 如何通过绝对XPath在Selenium中获取HTML元素的class属性值
优惠活动
大模型
产品
解决方案
定价
更多

如何通过绝对XPath在Selenium中获取HTML元素的class属性值

可以实现,操作方法如下

你可以直接通过现有XPath定位元素后获取class属性,无需依赖class本身的取值:

  • 首先使用你已有的绝对XPath定位到目标元素
  • 调用Selenium元素的get_attribute('class')方法即可获取当前元素的实时class值,即使class是动态生成的也不影响取值

代码示例(兼容新旧版本Selenium)

# 旧版本Selenium(支持find_element_by_xpath直接调用)
target_btn = driver.find_element_by_xpath('/html/body/bx-site/ng-component/div/sp-sports-ui/div/main/div/section/main/sp-path-event/div/sp-next-events/div/div/div[2]/div[1]/sp-coupon[1]/sp-multi-markets/section/section/sp-outcomes/sp-two-way-vertical[2]/ul/li[1]/sp-outcome/button')
btn_class = target_btn.get_attribute('class')
print(btn_class) # 输出当前class值,比如示例中的bet-btn
# Selenium 4.0+ 推荐写法(find_element_by_*系列方法已官方废弃)
from selenium.webdriver.common.by import By

target_xpath = '/html/body/bx-site/ng-component/div/sp-sports-ui/div/main/div/section/main/sp-path-event/div/sp-next-events/div/div/div[2]/div[1]/sp-coupon[1]/sp-multi-markets/section/section/sp-outcomes/sp-two-way-vertical[2]/ul/li[1]/sp-outcome/button'
target_btn = driver.find_element(By.XPATH, target_xpath)
btn_class = target_btn.get_attribute('class')

补充说明:如果页面加载较慢元素可能未渲染完成,建议搭配显式等待使用,避免出现元素定位失败的报错。

内容的提问来源于stack exchange,提问作者E. hendrix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 08:27:07