Ant*_*toG 11 python cookies selenium 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())
Run Code Online (Sandbox Code Playgroud)
问题是当我进入浏览器时,url即使我通过了请求会话生成的cookie ,我尝试访问时仍然存在登录验证.
如何修改上面的代码以通过身份验证网页?
任何人都可以帮我解决这个问题吗?
非常感谢您的帮助.
最好的祝福.
Ant*_*toG 18
我终于发现了问题所在.在post使用requests库发出请求之前,我应该首先通过浏览器的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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15730 次 |
| 最近记录: |