Python-请求,Selenium-登录时传递cookie [英] Python - Requests, Selenium - passing cookies while logging in

查看:524
本文介绍了Python-请求,Selenium-登录时传递cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to integrate python Selenium and Requests modules to authenticate on a website.

我正在使用以下代码:

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())

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

The problem is that when I enter the browser the login authentication is still there when I try to access the url even though I passed the cookies generated from the requests session.

如何修改上面的代码以通过身份验证网页?

How can I modify the code above to get through the authentication web-page?

可以有人帮我解决这个问题吗?

非常感谢您的帮助。

最好的问候。

Can anyone help me on this issue?
Your help is much appreciated.
Best Regards.

推荐答案

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

I finally found out what the problem was. Before making the post request with the requests library, I should have passed the cookies of the browser first. The code is as follows:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆