Selenium登录含OTP的网站后访问页面仍返回登录页问题求助
问题分析与解决:Selenium登录后访问页面仍跳转登录页
问题描述
爬取需登录(含OTP验证)的网站时,不使用Selenium可正常登录并访问页面;但通过Selenium完成账号密码输入、OTP验证登录后,调用driver.get访问目标页面却仍返回登录页。
用户代码如下:
登录代码
options = webdriver.ChromeOptions() #options.add_argument("--headless") # Runs Chrome in headless mode. options.add_argument('--no-sandbox') # Bypass OS security model options.add_argument('--disable-gpu') # applicable to windows os only options.add_argument('disable-infobars') options.add_argument("--disable-extensions") options.add_argument("AppData\\Local\\Google\\Chrome\\User Data\\Defaul") #Path to your chrome profile driver = webdriver.Chrome(executable_path="\\chromedriver.exe", chrome_options=options) #driver=webdriver.Chrome() site="https:xxxxxx" # call open browser function # Github credentials username = "username" password = "password" # head to github login page driver.get(site) # find username/email field and send the username itself to the input field driver.find_element_by_id("username").send_keys(username) time.sleep(20) # find password input field and insert password as well driver.find_element_by_id("password").send_keys(password) time.sleep(25) # click login button driver.find_element_by_id("btnLogin").click() otp="xxxxxx" driver.find_element_by_id("otp").send_keys(otp) driver.find_element_by_xpath("/html/body/div/div/div/div/button[1]").click()
会话保存代码
s = requests.Session() # Set correct user agent selenium_user_agent = driver.execute_script("return navigator.userAgent;") s.headers.update({"user-agent": selenium_user_agent}) for cookie in driver.get_cookies(): s.cookies.set(cookie['name'], cookie['value'], domain=cookie['domain'])
执行driver.get("https:mysite.com/page1")后仍返回登录页。
可能原因
- Chrome配置文件路径拼写错误,导致会话未正确持久化
- 登录流程未等待完成就执行页面跳转,会话状态未更新
- 网站通过
navigator.webdriver标识拦截Selenium自动化访问 - Cookie未被Driver正确携带,或缺少关键认证Cookie
解决方法
1. 修正Chrome配置文件路径
原路径存在拼写错误(Defaul少了最后一个t),需指定完整的用户数据目录,且确保Chrome未后台运行:
# 替换为你的实际系统用户名 options.add_argument(r"--user-data-dir=C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data") options.add_argument("--profile-directory=Default") # 指定使用Default配置文件
注意:使用用户配置文件前必须关闭本地所有Chrome实例,否则会出现端口占用冲突。
2. 用显式等待替代固定sleep,确保登录完成
固定time.sleep()不可靠,改用显式等待确认登录成功后的页面元素出现:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 点击OTP确认按钮后,等待登录成功标识元素(替换为实际页面存在的元素ID) WebDriverWait(driver, 30).until( EC.presence_of_element_located((By.ID, "logged-in-user-avatar")) ) # 确认登录状态后再访问目标页面 driver.get("https:mysite.com/page1")
3. 隐藏Selenium自动化特征
网站可能通过navigator.webdriver标记拦截,添加配置隐藏该特征:
# 初始化ChromeOptions时添加 options.add_argument("--disable-blink-features=AutomationControlled") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) # 初始化Driver后执行脚本覆盖webdriver属性 driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
4. 验证Cookie是否正确携带
登录完成后打印所有Cookie,确认关键认证Cookie存在:
# 登录成功后打印Cookie for cookie in driver.get_cookies(): print(f"Cookie: {cookie['name']} = {cookie['value']}") # 再访问目标页面 driver.get("https:mysite.com/page1")
若缺少关键Cookie,检查登录流程是否有未完成的跳转,或OTP验证后是否需要额外确认步骤。
5. 避免混用requests.Session与Selenium Driver
你保存了requests的会话,但后续使用的是Selenium Driver,两者是独立的会话。如果继续用Selenium操作,无需将Cookie导入requests,确保Driver自身的会话处于登录状态即可。
内容的提问来源于stack exchange,提问作者Dinh Truong Anh Phuong
相关产品推荐
相关产品推荐

