使用Selenium登录Twitch时遇错误,求解决方案
Twitch登录报错"Something went wrong. Please try again."解决建议
使用Selenium登录Twitch时,无论是脚本自动输入账号密码,还是手动输入凭据,都会弹出错误提示:"Something went wrong. Please try again.",无法完成登录,求解决建议。
原代码
from selenium import webdriver from selenium.webdriver.common.by import By import time def start_twitch_viewer(): PATH = r"./Local/twitch-stream-viewer/chromedriver" email = 'username@gmail.com' usr = 'Username' pswd = 'Password' chrome_options = webdriver.ChromeOptions() try: driver = webdriver.Chrome(PATH, options=chrome_options) driver.get("https://www.twitch.tv/ChannelName") driver.header_overrides = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"} except: return time.sleep(10) driver.find_element(By.CSS_SELECTOR, "div[class='Layout-sc-nxg1ff-0 csWXEI']").click() time.sleep(5) username=driver.find_element(By.CSS_SELECTOR, "input[id='login-username']") password=driver.find_element(By.CSS_SELECTOR, "input[id='password-input']") username.clear() password.clear() username.send_keys(usr) password.send_keys(pswd) time.sleep(5) driver.find_element(By.CSS_SELECTOR, "div[class='Layout-sc-nxg1ff-0 OZCSg']").click() time.sleep(1000) if __name__ == "__main__": start_twitch_viewer()
编辑补充:修改后的代码片段
根据@Lenta的建议修改后的代码:
chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("user-data-dir=/Users/usr/Library/Application Support/Google/Chrome") chrome_options.add_argument("profile-directory=Profile 3") chrome_options.add_experimental_option("detach", True) try: driver = webdriver.Chrome(executable_path=PATH, options=chrome_options) driver.set_window_position(0, 0) driver.set_window_size(1440, 900) driver.get("https://www.twitch.tv/user") except: return
解决建议
使用已登录的浏览器配置文件
你修改后的代码思路正确,需注意:- 将路径中的
usr替换为你的实际系统用户名 - 确认
Profile 3是你已经手动登录过Twitch的浏览器配置文件 - 启动Selenium前关闭所有Chrome窗口,避免进程冲突
- 将路径中的
修复用户代理设置
原代码中driver.header_overrides的写法无效,需通过ChromeOptions添加:chrome_options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36")替换动态元素选择器
原代码中依赖动态生成的class名(如Layout-sc-nxg1ff-0 csWXEI)易失效,改用更稳定的选择器:- 登录按钮:
button[data-a-target="login-button"] - 用户名输入框:
input#login-username - 密码输入框:
input#password-input - 登录提交按钮:
button[data-a-target="login-submit-button"]
- 登录按钮:
添加反检测参数
Twitch会识别Selenium,添加以下参数降低被检测概率:chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option('useAutomationExtension', False)处理人机验证
若仍报错,大概率触发了人机验证:- 在代码中添加足够长的等待时间(如
time.sleep(30)),手动完成验证后继续执行 - 优先使用已登录的浏览器配置文件,跳过登录验证步骤
- 在代码中添加足够长的等待时间(如
内容的提问来源于stack exchange,提问作者Piero
相关产品推荐
相关产品推荐

