Error when loading cookies into a Python request session

前端 未结 6 1964
鱼传尺愫
鱼传尺愫 2020-11-27 08:00

I am trying to load cookies into my request session in Python from selenium exported cookies, however when I do it returns the following error: \"\'list\' object has no attr

6条回答
  •  温柔的废话
    2020-11-27 08:49

    You can get cookies and use only name/value. You'll need headers also. You can get them from dev tools or by using proxy.

    Basic example:

    driver.get('https://website.com/')
    
    # ... login or do anything
    
    cookies = {}
    for cookie in driver.get_cookies():
        cookies[cookie['name']] = cookie['value']
    # Write to a file if need or do something
    # import json
    # with open("cookies.txt", 'w') as f:
    #    f.write(json.dumps(cookies))
    

    And usage:

    # Read cookies from file as Dict
    # with open('cookies.txt') as reader:
    #     cookies = json.loads(reader.read())
    
    # use cookies
    response = requests.get('https://website.com/', headers=headers, cookies=cookies)
    

    Stackoverflow headers example, some headers can be required some not. You can find information here and here. You can get request headers using dev tools Network tab:

    headers = {
        'authority': 'stackoverflow.com',
        'pragma': 'no-cache',
        'cache-control': 'no-cache',
        'dnt': '1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',
        'sec-fetch-user': '?1',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-mode': 'navigate',
        'referer': 'https://stackoverflow.com/questions/tagged?sort=Newest&tagMode=Watched&uqlId=8338',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'ru,en-US;q=0.9,en;q=0.8,tr;q=0.7',
    }
    

提交回复
热议问题