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

如何解决Selenium运行报错AttributeError: 'list'对象无'text'属性

错误原因
  • 核心错误:你调用的driver.find_elements_by_class_name()是复数查询方法,返回值是符合类名条件的所有WebElement对象组成的列表,列表类型本身不存在text属性,因此触发AttributeError。
  • 调用逻辑错误:Selenium中WebElement对象获取文本的text是属性,不是可调用方法,不需要加()执行。
  • 语法错误:你给出的代码中print(contact.text()缺少右括号,运行时也会触发语法报错。
修复方案

根据你的使用场景选择对应修复方式:

场景1:仅需获取单个匹配的联系人元素

将复数查询改为单数查询,同时修正text的调用方式、补全括号:

from selenium import webdriver
from selenium.webdriver.common import keys
import time

driver = webdriver.Firefox(executable_path="geckodriver.exe")
driver.get("https://web.whatsapp.com/")
input("Qr Code Done? : ")
driver.implicitly_wait(10)

# 改为单数查询方法,只返回第一个匹配的元素
contact = driver.find_element_by_class_name('_3q9s6')
# text是属性无需加括号,补全右括号
print(contact.text)

场景2:批量导出所有匹配的联系人姓名

遍历find_elements返回的列表,逐个获取每个元素的text属性:

from selenium import webdriver
from selenium.webdriver.common import keys
import time

driver = webdriver.Firefox(executable_path="geckodriver.exe")
driver.get("https://web.whatsapp.com/")
input("Qr Code Done? : ")
driver.implicitly_wait(10)

contacts = driver.find_elements_by_class_name('_3q9s6')
# 遍历列表输出每个联系人姓名
for contact in contacts:
    print(contact.text)

补充说明:如果使用Selenium 4.0及以上版本,原find_element_by_*/find_elements_by_*系列方法已被弃用,建议改为以下写法:
先导入依赖:from selenium.webdriver.common.by import By
单个查询替换为:driver.find_element(By.CLASS_NAME, '_3q9s6')
批量查询替换为:driver.find_elements(By.CLASS_NAME, '_3q9s6')

内容的提问来源于stack exchange,提问作者Kirito-Kun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:30:04