0

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 ?

kingcope
  • 1,121
  • 4
  • 19
  • 36
  • Almost duplicate: [How to save and load cookies using Python + Selenium WebDriver - Stack Overflow](https://stackoverflow.com/questions/15058462/how-to-save-and-load-cookies-using-python-selenium-webdriver) – user202729 Jan 02 '21 at 01:52

2 Answers2

3

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})
Florent B.
  • 41,537
  • 7
  • 86
  • 101
0

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:
Bryan
  • 295
  • 1
  • 2
  • 9