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

如何提取页面所有按钮文本?解决list无getText属性的AttributeError报错

解决方法

错误原因

driver.find_elements(By.TAG_NAME, 'button')返回的是WebElement对象的列表,而getText()是单个元素的方法(另外Python Selenium中获取文本的属性是.text,不是getText()——这是Java Selenium的写法),直接在列表上调用该方法会触发AttributeError。

正确代码

方式1:列表推导式(简洁写法)

all_buttons_text = [button.text for button in driver.find_elements(By.TAG_NAME, 'button')]

方式2:循环遍历(更直观)

all_buttons = driver.find_elements(By.TAG_NAME, 'button')
all_buttons_text = []
for button in all_buttons:
    # 可选:过滤空文本的按钮
    if button.text.strip():
        all_buttons_text.append(button.text)

运行后,all_buttons_text就是所有按钮文本组成的列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:55:14