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

使用Selenium开发Twitter Bot时Chrome窗口闪退的解决方法

修复Selenium Chrome窗口启动即关闭的问题

以下是针对你遇到的Chrome窗口一启动就关闭问题的具体修复方案:

核心原因及解决步骤

1. 匹配ChromeDriver与Chrome浏览器版本

ChromeDriver版本必须和本地Chrome浏览器主版本号完全一致,否则会出现兼容性问题导致窗口异常关闭:

  • 查看Chrome版本:打开Chrome → 右上角三点 → 设置 → 关于Chrome,获取版本号(如118.0.5993.70)。
  • 下载对应版本的ChromeDriver,将其放在项目目录下,或添加到系统环境变量PATH中。

2. 修正Selenium初始化参数

新版本Selenium已弃用chrome_options参数,改用options;同时添加detach选项可强制浏览器在程序执行后保持打开状态。

修改后的完整代码

from userinfo import username, password 
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
# Selenium 4.x推荐引入Service类管理驱动
from selenium.webdriver.chrome.service import Service

class TwitterBot:
    def __init__(self, username, password):
        self.browser_profile = webdriver.ChromeOptions()
        self.browser_profile.add_experimental_option('prefs', {'intl.accept_languages': 'en,en_US'})
        # 添加detach选项,阻止浏览器自动关闭
        self.browser_profile.add_experimental_option("detach", True)
        # 使用Service类指定驱动路径(Selenium 4.x标准写法)
        service = Service('chromedriver.exe')
        self.browser = webdriver.Chrome(service=service, options=self.browser_profile)
        self.username = username
        self.password = password
    
    def sign_in(self):
        self.browser.get("https://twitter.com/i/flow/login")
        
        time.sleep(2)
        self.browser.maximize_window()
        # 注意:XPATH可能随页面更新失效,后续建议用By.NAME/By.CSS_SELECTOR更稳定的定位方式
        username_input = self.browser.find_element(By.XPATH, "//*[@id='react-root']/div/div/div/main/div/div/div/div[2]/div[2]/div/div[5]/label/div/div[2]/div/input")
        username_input.click()
        username_input.send_keys(self.username)
        username_input.send_keys(Keys.ENTER)
        time.sleep(2)
        password_input = self.browser.find_element(By.XPATH, "//*[@id='react-root']/div/div/div/main/div/div/div/div[2]/div[2]/div[1]/div/div/div/div[3]/div/label/div/div[2]/div[1]/input")
        password_input.click()
        password_input.send_keys(self.password)
        password_input.send_keys(Keys.ENTER)
        
giris = TwitterBot(username, password)
giris.sign_in()

额外优化建议

  • 替换硬编码XPATH:Twitter页面结构可能随时更新,硬编码XPATH易失效,建议改用By.NAME或By.CSS_SELECTOR定位元素。
  • 替换time.sleep():使用WebDriverWait实现显式等待,提升代码稳定性和执行效率。

内容的提问来源于stack exchange,提问作者Alimcan Çekim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:45:13