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

使用Selenium自动化Twitter登录时遇DeprecationWarning与NoSuchElementException

解决Twitter登录自动化的两个问题

1. 解决DeprecationWarning警告

  • 原因:Selenium 4.x版本已弃用直接通过executable_path参数传递驱动路径的方式,要求使用Service对象。
  • 修复步骤:
    • 导入Service类:from selenium.webdriver.chrome.service import Service
    • 创建Service实例包裹驱动路径,再传入webdriver.Chrome

2. 解决NoSuchElementException异常

该异常核心原因是元素定位方式过于脆弱或页面未加载完成就尝试操作元素,修复方案如下:

  • 替换绝对XPath:使用相对定位(如元素的name属性、文本内容),避免页面结构变动导致定位失效
  • 改用显式等待:替代固定time.sleep(),等待元素可见/可点击后再操作,适配页面加载延迟
  • 匹配实际登录流程:Twitter当前登录流程为「输入邮箱/用户名→点击下一步→输入密码→登录」,需按流程分步操作

修复后的完整代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

# 初始化浏览器驱动(解决DeprecationWarning)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get("https://twitter.com/i/flow/login")
driver.maximize_window()

# 登录凭证
email = "your-email-address"
password = "your-password"

wait = WebDriverWait(driver, 10)  # 设置10秒显式等待超时

# 输入邮箱/用户名
email_field = wait.until(EC.visibility_of_element_located((By.NAME, "text")))
email_field.send_keys(email)

# 点击下一步按钮
next_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//span[text()="下一步"]')))
next_button.click()

# 输入密码
password_field = wait.until(EC.visibility_of_element_located((By.NAME, "password")))
password_field.send_keys(password)

# 点击登录按钮
login_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//span[text()="登录"]')))
login_button.click()

# 可选:停留查看结果后关闭浏览器
time.sleep(5)
driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:16:20