bonfy / problems

record problems I have met and solved
2 stars 1 forks source link

load session and cookies from Selenium browser to requests library in Python #9

Open bonfy opened 7 years ago

bonfy commented 7 years ago

load session and cookies from Selenium browser to requests library in Python

selenium login in the website and get the cookie need to load this cookie to requests

selenium cookie type is list[dict]

like:

[{'domain': '.leetcode.com',
  'expiry': 1554816297,
  'httpOnly': False,
  'name': '_ga',
  'path': '/',
  'secure': False,
  'value': 'GA1.2.1747795713.1491744295'},
 {'domain': '.leetcode.com',
  'expiry': 1492953896.192421,
  'httpOnly': True,
  'name': 'LEETCODE_SESSION',
  'path': '/',
  'secure': True,
  'value': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImJvbmZ5IiwidXNlcl9zbHVnIjoiYm9uZnkiLCJfYXV0aF91c2VyX2lkIjoiNTEzMzUyIiwidGltZXN0YW1wIjoiMjAxNy0wNC0wOSAxMzoyNDo1NS45NjQwOTErMDA6MDAiLCJfYXV0aF91c2VyX2JhY2iMWU1ZTFjNDdlYjE4NTc3MzA3NmM2MCIsImVtYWlsIjoiYm9uZnlnaXRodWJAMTYzLmNvbSJ9.kFOF2rckv67d5MRsaG5XmjGQIeOKh1HoiF_woTi5li4'},
 {'domain': 'leetcode.com',
  'expiry': 1523193896.192364,
  'httpOnly': False,
  'name': 'csrftoken',
  'path': '/',
  'secure': True,
  'value': 'lLFixwn81hSSRlmUxkzUfCNdC4byTnNXi9eCg4xussn3VeiCQ03049'},
 {'domain': '.leetcode.com',
  'expiry': 1491744354,
  'httpOnly': False,
  'name': '_gat',
  'path': '/',
  'secure': False,
  'value': '1'}]
bonfy commented 7 years ago

http://stackoverflow.com/questions/29563335/how-do-i-load-session-and-cookies-from-selenium-browser-to-requests-library-in-p

cookies = driver.get_cookies()

This returns a set of cookie dictionaries for your session.

Next, set those cookies in requests:

s = requests.Session()
for cookie in cookies:
    s.cookies.set(cookie['name'], cookie['value'])