无法使用我在请求模块中从浏览器获得的cookie

时间:2018-12-03 13:59:32

标签: python selenium python-requests

因此,我试图通过Selenium从浏览器获取cookie,并通过requests模块在​​控制台中将其用于进一步的请求。 示例代码是这样的:

from selenium import webdriver
import requests


header = {"User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
s=requests.session()
driver=webdriver.Chrome()
driver.get("https://www.google.com/")  #using random website
x=driver.get_cookies()
print(x)
r=s.get("https://www.google.com/", headers=header, cookies=x)
print(r.status_code)

但是在制作get request时,我总是遇到以下问题:

cookieselenium.py", line 19, in <module>
    r=s.get("https://www.bstn.com/", headers=header, cookies=x)
  File "C:\Users\patrick\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\sessions.py", line 546, in get
    return self.request('GET', url, **kwargs)
  File "C:\Users\patrick\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "C:\Users\patrick\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\sessions.py", line 440, in prepare_request
    cookies = cookiejar_from_dict(cookies)
  File "C:\Users\patrick\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\cookies.py", line 524, in cookiejar_from_dict
    cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
TypeError: list indices must be integers or slices, not dict

我真的不知道如何解决这个问题,因此,我非常感谢您提供任何有用的答案...

1 个答案:

答案 0 :(得分:0)

您需要重建cookie并仅使用namevalue

cookies = {cookie['name']:cookie['value'] for cookie in x}
r=s.get("https://www.google.com/", headers=header, cookies=cookies)

# Or
for cookie in x:
    s.cookies.set(cookie['name'], cookie['value'])
r=s.get("https://www.google.com/", headers=header)