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

Python+Selenium中get_attribute方法失效问题求助

Selenium获取网页span元素问题解决

错误原因

你用get_attribute('span')完全用错了方法——这个函数是用来获取元素的HTML属性(比如class、id、value这类写在标签里的属性),但broker-details这个div标签本身根本没有span属性,所以返回空值,和那个空白类没关系。

正确获取span元素的方法

1. 从父元素内批量获取所有span

先拿到目标父元素,再在它内部查找所有span标签:

# 初始化驱动(你的原有代码)
driver = webdriver.Chrome(service=service, options=options)

# 获取第一个broker-details元素
broker_box = driver.find_elements(By.CLASS_NAME, 'broker-details')[0]
# 在父元素内查找所有span标签
all_spans = broker_box.find_elements(By.TAG_NAME, 'span')
# 遍历输出每个span的文本(strip()用来去掉多余空格)
for span in all_spans:
    print(span.text.strip())

执行后会依次输出:123456-X、18/03/2021、Active

2. 精准定位单个特定span

如果只需要某一个span的内容(比如CODE对应的),可以用XPath或CSS选择器直接定位:

获取CODE对应的span文本
code_value = driver.find_element(By.XPATH, "//div[@class='broker-details']//strong[text()='CODE: ']/following-sibling::span").text.strip()
print(code_value)  # 输出:123456-X
获取Registration Date对应的span文本
reg_date = driver.find_element(By.XPATH, "//div[@class='broker-details']//strong[text()='Registration Date: ']/following-sibling::span").text.strip()
print(reg_date)  # 输出:18/03/2021
获取Situation对应的span文本
situation = driver.find_element(By.XPATH, "//div[@class='broker-details']//strong[text()='Situation: ']/following-sibling::span").text.strip()
print(situation)  # 输出:Active

关于那个空白类

那个<div class=" "> 不需要特意引用,我们的选择器会自动穿透这个层级,直接定位到需要的元素。

内容的提问来源于stack exchange,提问作者Lucas Duarte

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:25:06