Python - 请求,Selenium - 在登录时传递 cookie

Posted

技术标签:

【中文标题】Python - 请求,Selenium - 在登录时传递 cookie【英文标题】:Python - Requests, Selenium - passing cookies while logging in 【发布时间】:2017-06-24 14:05:31 【问题描述】:

我想集成 python Selenium 和 Requests 模块以在网站上进行身份验证。

我正在使用以下代码:

import requests
from selenium import webdriver

driver = webdriver.Firefox()
url = "some_url" #a redirect to a login page occurs
driver.get(url) #the login page is displayed

#making a persistent connection to authenticate
params = 'os_username':'username', 'os_password':'password'
s = requests.Session()
resp = s.post(url, params) #I get a 200 status_code

#passing the cookies to the driver
driver.add_cookie(s.cookies.get_dict())

问题是当我进入浏览器时,当我尝试访问url 时,登录身份验证仍然存在,即使我传递了从请求会话生成的cookie。

如何修改上面的代码才能通过认证网页?

谁能帮我解决这个问题? 非常感谢您的帮助。 最好的问候。

【问题讨论】:

这是两个不同的客户端,有两个不同的会话——你不能以这种方式混合它们。尝试在requests 上完成脚本或在selenium 上完成。另外您可能需要尝试pypi.python.org/pypi/selenium-requests 我认为通过 cookie 可以解决问题,因为我使用请求会话生成的 cookie 打开浏览器。不是这样吗? 尝试使用相同的User-Agent 信息更新headers,例如"User-Agent": "Mozilla/5.0" 我遇到了同样的问题 我的猜测是您将 POST 请求发送到错误的 URL。许多网站使用不同的 URL(与登录登陆 URL 相比)进行身份验证 【参考方案1】:

我对这段代码有一些问题,因为它为原始浏览器 cookie 设置了双重 cookie(登录之前),然后我通过在将登录 cookie 设置为原始之前清理 cookie 来解决这个问题。我使用了这个命令:

driver.delete_all_cookies()

【讨论】:

【参考方案2】:

我终于找到了问题所在。 在使用requests 库发出post 请求之前,我应该先传递浏览器的cookie。 代码如下:

import requests
from selenium import webdriver

driver = webdriver.Firefox()
url = "some_url" #a redirect to a login page occurs
driver.get(url)

#storing the cookies generated by the browser
request_cookies_browser = driver.get_cookies()

#making a persistent connection using the requests library
params = 'os_username':'username', 'os_password':'password'
s = requests.Session()

#passing the cookies generated from the browser to the session
c = [s.cookies.set(c['name'], c['value']) for c in request_cookies_browser]

resp = s.post(url, params) #I get a 200 status_code

#passing the cookie of the response to the browser
dict_resp_cookies = resp.cookies.get_dict()
response_cookies_browser = ['name':name, 'value':value for name, value in dict_resp_cookies.items()]
c = [driver.add_cookie(c) for c in response_cookies_browser]

#the browser now contains the cookies generated from the authentication    
driver.get(url)

【讨论】:

反过来会怎么样?创建与驱动程序的连接并将 auth cookie 传递给驱动程序?

以上是关于Python - 请求,Selenium - 在登录时传递 cookie的主要内容,如果未能解决你的问题,请参考以下文章

Python 上的 Selenium - 提交方法似乎无法正确发送请求?

将会话ID从Selenium传递到Python请求

Python3请求库Selenium的安装教程

Python3请求库Selenium的安装教程

selenium+python

如何识别 ReCaptcha V2 的 32 位数据站点密钥以使用 Selenium 和 Python 请求以编程方式获取有效响应?