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

使用Selenium WebDriver在Twitter批量关注用户失败问题求助

解决方案:修复Selenium无法触发Twitter关注按钮点击的问题

核心问题分析

你的脚本存在几个关键问题导致点击无效:

  • 定位Follow按钮时选择了<span>元素,而非实际可交互的按钮根节点(div[@role="button"])
  • XPath路径过于冗余,容易因页面结构小变化失效,且未限定在当前滚动容器内查找(用//会全局搜索,可能匹配到弹窗外的元素)
  • 滚动容器定位错误,Twitter关注列表的滚动区域不是UserCell,而是弹窗内的滚动容器
  • 仅用presence_of_element_located无法确保元素处于可交互状态

修正后的代码

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

# 处理关注列表的关注逻辑
while True:
    try:
        # 定位正确的滚动容器(Twitter弹窗的滚动区域)
        scroll_container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//div[@role="dialog"]//div[@data-testid="scrollable"]'))
        )
        
        # 滚动到底部,加载更多用户
        last_height = driver.execute_script("return arguments[0].scrollHeight", scroll_container)
        driver.execute_script("arguments[0].scrollTo(0, arguments[0].scrollHeight);", scroll_container)
        time.sleep(2)
        new_height = driver.execute_script("return arguments[0].scrollHeight", scroll_container)
        
        # 定位当前可视区域内的所有未关注按钮(限定在滚动容器内查找)
        follow_buttons = WebDriverWait(scroll_container, 10).until(
            EC.presence_of_all_elements_located(
                (By.XPATH, './/div[@data-testid="UserCell"]//div[@role="button" and .//span[text()="Follow"]]')
            )
        )
        
        if not follow_buttons or last_height == new_height:
            break  # 没有更多按钮或滚动到底部,退出循环
        
        # 逐个点击关注按钮
        for button in follow_buttons:
            try:
                # 等待按钮可点击
                WebDriverWait(driver, 5).until(EC.element_to_be_clickable(button))
                # 滚动到按钮可见区域(避免被弹窗头部遮挡)
                driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
                time.sleep(1)
                # 用JS点击替代直接click,避免元素遮挡或交互问题
                driver.execute_script("arguments[0].click();", button)
                time.sleep(2)  # 给Twitter服务器响应时间,避免触发反爬
            except Exception as e:
                print(f"点击按钮失败: {e}")
                continue
    except Exception as e:
        print(f"循环出错: {e}")
        break

关键改进点

  • 正确定位滚动容器:使用data-testid="scrollable"定位弹窗的滚动区域,确保滚动操作有效加载更多用户
  • 精准定位可交互按钮:直接定位div[@role="button"](实际可点击的元素),并通过相对路径.限定在滚动容器内查找,避免全局匹配
  • 增强等待逻辑:用element_to_be_clickable确保按钮处于可交互状态,而非仅存在于DOM中
  • 优化点击方式:使用execute_script模拟点击,避免因元素被遮挡、Z-index问题导致的点击失效
  • 添加反爬防护:增加合理的等待时间,避免短时间内大量操作触发Twitter的反机制
  • 滚动终止判断:通过对比滚动前后的高度,判断是否已加载完所有用户

额外排查建议

  • 检查是否存在登录后的验证弹窗(如手机号验证),这类弹窗会阻断后续操作
  • 确保浏览器驱动版本与浏览器版本完全匹配,版本不兼容会导致元素交互异常
  • 启用浏览器开发者工具,查看点击按钮时的控制台错误,是否有JS报错影响交互

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:32:35