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

标签 python selenium cookies python-requests

我想集成 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 时,即使我传递了从请求 session 生成的 cookie,登录身份验证仍然存在。

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

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

最佳答案

我终于找到问题所在了。 在使用 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)

关于Python - 请求,Selenium - 登录时传递 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42087985/

相关文章:

java - 如果别的??尝试??我需要方法方面的帮助

java - 与 .Net 共享 Java HTTP session

python - python中数字范围的正则表达式

python - 减去 pandas 数据框,同时保留一些列完好无损

python-2.7 - selenium浏览器点击后刷新scrapy响应

php - 在 iPhone 网络应用程序上维护 PHP session

javascript - 如何检测一个unique visitor是unique的?

python - Pandas :根据开始/结束日期聚合

python - Python 中的 'in' 运算符是 "lazy"吗?

java - 使用 WebDriver 在基于 CSS 的菜单中选择一个选项