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

如何修复Python Selenium中TypeError: 'FirefoxWebElement' object is not subscriptable报错

报错原因

你调用driver.find_elements_by_class_name('zoWT4')返回的是FirefoxWebElement对象组成的列表,遍历这个列表时,每一个number本身就是单个元素对象,不支持[0]下标操作,这是触发TypeError: 'FirefoxWebElement' object is not subscriptable的直接原因。

修正后的代码(含保存到txt的功能)
from selenium import webdriver
import time

driver = webdriver.Firefox(executable_path="geckodriver.exe")
driver.get("https://web.whatsapp.com/")
input("扫码完成后按回车键继续: ")
driver.implicitly_wait(10)

phnenumbers = driver.find_elements_by_class_name('zoWT4')

# 打开文件写入结果
with open('whatsapp_contacts.txt', 'w', encoding='utf-8') as f:
    for number in phnenumbers:
        # 移除多余的[0]直接取text属性
        contact_text = number.text
        print(contact_text)
        f.write(contact_text + '\n')

driver.quit()
补充注意事项
  • 如果你需要获取全部8000条联系人,直接调用定位方法只能拿到当前可视区域的内容,需要添加滚动加载逻辑,滚动联系人列表直到所有元素加载完成再抓取
  • zoWT4是WhatsApp Web的前端动态生成类名,平台更新后类名可能变化,抓取失效时可以换成XPath等更稳定的定位方式
  • 操作时不要频繁刷新页面,避免触发反爬机制导致账号限制

内容的提问来源于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:57:04