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

使用Selenium Python登录后站点无法访问,求绕过方案

问题描述

使用Selenium-Python抓取需要登录的网站时,点击登录按钮后页面显示无法访问(截图如下):
无法访问页面

已尝试的代码如下:

driver = webdriver.Chrome()

url = 'https://www.company.ai/account/login'

driver.get(url)
# driver.implicitly_wait(10)

time.sleep(5)
username = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='username']")))
username.send_keys("EMAIL_ADDRESS")

password = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[placeholder='Password']")))
password.send_keys("PASSWORD")

time.sleep(5)

button = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']")))

# driver.implicitly_wait(5)
button.click()

time.sleep(10)

# Extract data from the dynamically loaded content
newURL = 'url1.com'
data = driver.get(newURL)
driver.implicitly_wait(10)
print(data.title)

# driver.quit()
解决方案
  • 模拟真实浏览器环境,规避自动化检测:Selenium默认配置易被网站识别,可通过添加浏览器参数伪装成普通用户:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
# 设置真实User-Agent
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")
# 禁用自动化标识
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

driver = webdriver.Chrome(options=options)
  • 替换硬编码sleep为显式等待:固定时长的sleep会导致操作节奏生硬,改用WebDriverWait等待登录后的页面状态,比如等待目标页面的特征元素加载完成:
# 点击登录后,等待跳转页面的核心元素出现
WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CSS_SELECTOR, "目标页面的唯一元素选择器")))
  • 通过Cookie直接登录,跳过手动输入流程:先手动登录网站,导出登录状态的Cookie,再用Selenium加载Cookie直接进入已登录状态,避免触发登录环节的反爬:
driver.get("https://www.company.ai/")  # 先访问网站主页初始化Cookie容器
# 添加导出的Cookie(需替换为实际获取的Cookie键值对和域名)
driver.add_cookie({"name": "auth_token", "value": "your_auth_value", "domain": ".company.ai"})
driver.refresh()  # 刷新后即可进入登录状态
  • 检查并更换IP地址:若多次尝试后仍无法访问,大概率是当前IP被网站封禁,可配置代理IP更换访问源:
options.add_argument('--proxy-server=http://your-proxy-ip:port')

内容的提问来源于stack exchange,提问作者Vinit Panchal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:45:15