python+selenium获取cookie session,Python-请求,Selenium-登录时传递cookie

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

I am using the following code:

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

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.

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值