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

PythonAnywhere中Selenium无法正常访问Discord的问题求助

问题

在PythonAnywhere平台使用Selenium工具访问Discord时,出现「Connection Problems? Let us know」的连接错误。推测原因是Discord使用了discord.com以外的其他域名,而这些域名未被列入PythonAnywhere的出站白名单。

使用的脚本如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
import time

driver = webdriver.Chrome(options=chrome_options)
driver.get("http://discord.com/login")
print("waiting")
time.sleep(10)

komut = """function login(token) {
setInterval(() => {
document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = 
`"${token}"`
}, 50);
setTimeout(() => {
location.reload();
}, 2500);
}

login('discord token here')"""

driver.execute_script(komut)
print("executed")
time.sleep(5)
driver.get("http://discord.com/channels/@me")
解决方案
  • 确认白名单域名:Discord运行依赖多个子域名,比如cdn.discordapp.com、discordapp.com、media.discordapp.net等。需要检查这些域名是否在PythonAnywhere的出站白名单中,若未包含,可通过PythonAnywhere的支持渠道提交添加申请。
  • 优化浏览器请求配置:在ChromeOptions中添加模拟正常浏览器的User-Agent,避免被Discord的反爬机制拦截:
    chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
    
  • 改用正规登录方式:当前使用的token注入登录方式已被Discord的反作弊机制检测,大概率会触发访问限制。建议替换为账号密码登录流程:
    # 先导入必要模块
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # 替换原token注入代码
    WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.NAME, "email")))
    driver.find_element(By.NAME, "email").send_keys("你的Discord邮箱")
    driver.find_element(By.NAME, "password").send_keys("你的Discord密码")
    driver.find_element(By.XPATH, "//button[@type='submit']").click()
    time.sleep(5)
    
  • 使用智能等待替代固定延迟:time.sleep的固定等待时间不稳定,改用WebDriverWait等待页面元素加载完成,提升脚本可靠性:
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # 等待登录页面的邮箱输入框出现
    WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.NAME, "email")))
    

内容的提问来源于stack exchange,提问作者Mehmet Tok

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 22:38:12