Error when loading cookies into a Python request session

前端 未结 6 1974
鱼传尺愫
鱼传尺愫 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 08:58

    Since you are replacing session.cookies (RequestsCookieJar) with a list which don't have those attributes, it won't work.

    You can import those cookies one by one by using:

    for c in your_cookies_list:
       initial_state.cookies.set(name=c['name'], value=c['value'])
    

    I've tried loading the whole cookie but it seems like requests doesn't recognize those ones and returns:

    TypeError: create_cookie() got unexpected keyword arguments: ['expiry', 'httpOnly']
    

    requests accepts expires instead and HttpOnly comes nested within rest

    Update:

    We can also change the dict keys for expiry and httpOnly so that requests correctly load them instead of throwing an exception, by using dict.pop() which deletes an item from dict by the key and returns the value of deleted key so after we add a new key with deleted item value then unpack & pass them as kwargs:

    for c in your_cookies_list:
        c['expires'] = c.pop('expiry')
        c['rest'] = {'HttpOnly': c.pop('httpOnly')}
        initial_state.cookies.set(**c)
    

提交回复
热议问题