如何将会话和Cookie从Selenium浏览器加载到Python中的请求库?

前端之家收集整理的这篇文章主要介绍了如何将会话和Cookie从Selenium浏览器加载到Python中的请求库?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何从Selenium浏览器加载会话和Cookie?以下代码
import requests

cookies = [{u'domain': u'academics.vit.ac.in',u'name': u'ASPSESSIONIDAEQDTQRB',u'value': u'ADGIJGJDDGLFIIOCEZJHJCGC',u'expiry': None,u'path': u'/',u'secure': True}]
response = requests.get(url2,cookies=cookies)

给我以下例外:

Traceback (most recent call last):
  File "F:\PYTHON\python_scripts\cookies\cookies3.py",line 23,in <module>
    response = requests.get(url2,cookies=cookies)
  File "C:\Python27\lib\site-packages\requests\api.py",line 68,in get
    return request('get',url,**kwargs)<br/>
  File "C:\Python27\lib\site-packages\requests\sessions.py",line 450,in request
    prep = self.prepare_request(req)
    cookies = cookiejar_from_dict(cookies)
  File "C:\Python27\lib\site-packages\requests\cookies.py",line 439,in cookiejar_from_dict
    cookiejar.set_cookie(create_cookie(name,cookie_dict[name]))
TypeError: list indices must be integers,not dict

解决方法

首先,您必须从驱动程序实例获取Cookie:
cookies = driver.get_cookies()

这将为您的会话返回set of cookie dictionaries.

接下来,在请求中设置这些cookie:

s = requests.Session()
for cookie in cookies:
    s.cookies.set(cookie['name'],cookie['value'])
原文链接:https://www.f2er.com/html/224849.html

猜你在找的HTML相关文章