web-dev-qa-db-ja.com

Python-リクエスト、Selenium-ログイン中にクッキーを渡す

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

問題は、リクエストセッションから生成されたCookieを渡したとしても、ブラウザに入ると、urlにアクセスしようとしてもログイン認証が残っていることです。

上記のコードを変更して認証Webページを取得するにはどうすればよいですか?

誰もこの問題で私を助けることができますか?
ご協力ありがとうございます。
宜しくお願いします。

9
AntoG

私は最終的に問題が何であるかを見つけました。 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)
17
AntoG