Home > Blockchain >  Chromedriver: How to obtain login session for later bypass of login in python
Chromedriver: How to obtain login session for later bypass of login in python

Time:08-08

My code does a curl to get a login session token to a website.

I then want to store the details of the session so that I can then use chromedriver to launch the dashboard page of the website without needing to login again.

Is there a way to reuse the token in the ChromeDriver object?

CodePudding user response:

When you're saying session token, you're actually referring to cookies. You can save the cookies of the current ChromeDriver session by using driver.manage() to handle cookies, save them on file, access them by name or adding them to the current ChromeDriver instance. It is explained pretty well here.

CodePudding user response:

You can use the Requests library in place of curl.

import requests

post_url = 'http://example.com/login'
payload = { 'key' : 'value' }
headers = {}

cookies_before = set(session.cookies.get_dict().items())

response = session.post(post_url, data=payload, headers=headers)

cookies_after = set(session.cookies.get_dict().items())

cookies_set = cookies_after - cookies_before

At this point cookies_set contains key, value tuples. You could use pickle to serialize the data if required.

Afterwards you can add the cookie information to the webdriver's browsing context.

from selenium import webdriver

driver = webdriver.Chrome()

driver.get('http://www.example.com/404')

for t in cookies_set:
     key, value = t
     driver.add_cookie({'name': key, 'value': value})
  • Related