python-requests cookies export to selenium

喜你入骨 提交于 2020-06-03 07:54:58

问题


I want to login to website whit requests library and after export cookies to selenium, I'm write this code :

import requests
from selenium import webdriver

session=requests.Session()

MyHeaderss = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.32 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.32", "X-GWT-Permutation" : "6FEFBE57C6E73F0AB33BD5A4E17945DE", "Content-Type":"text/x-gwt-rpc; charset=utf-8"}

login_data = '''https://www.cartetitolari.mps.it/portaleTitolari/|FEAC78FFDF81D6121438D70986AF1C41|portale.titolari.client.service.PTService|login|portale.titolari.client.common.login.LoginRequest/3583069702|xxxxxxxxxxx|matteosbragia1984|'''


ra0=session.post('https://www.cartetitolari.mps.it/portaleTitolari/service', data=login_data, headers=MyHeaderss)
print ra0.content

profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.32 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.32")

driver = webdriver.Firefox()
driver.add_cookie(session.cookies.get_dict())

driver.get("https://www.cartetitolari.mps.it/portaleTitolari/downloadeco?id=0")

The code work, but not successfully export session/cookies in selenium, when the page loads are required to login! Where I'm wrong ?


回答1:


You first need to navigate to the page to set the domain, then add each cookie by iterating the cookie jar:

driver.get("https://www.cartetitolari.mps.it/portaleTitolari/titolari.html")

for c in session.cookies :
    driver.add_cookie({'name': c.name, 'value': c.value, 'path': c.path, 'expiry': c.expires})



回答2:


I had a similar issue. Watching with the developer window, I could see that after login a cookie was being sent but then the page via javascript or something else was redirecting before returning control to the program. So, I was unable to get that cookie and save it off.

After more research I realised that the program was starting with a clean session each time (this answer helped a lot) so the persistent cookies weren't persistent at all. It took further research, but giving selenium (via splinter) a profile to work with resolved my issue.

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("user-data-dir=" + tdir + "/chrome-session")
chrome_options.add_argument("--profile-directory=Default")
with Browser('chrome', headless=True, options=chrome_options) as browser:


来源:https://stackoverflow.com/questions/37490665/python-requests-cookies-export-to-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!