Putting a `Cookie` in a `CookieJar`

前端 未结 10 1454
谎友^
谎友^ 2020-11-30 01:45

I\'m using the new Python Requests library to make http requests. I obtain a cookie from the server as text. How do I turn that into a CookieJar with the cookie

10条回答
  •  失恋的感觉
    2020-11-30 02:25

    Assuming that you have requested for url and you got headers as response. Type type of url is string. Type type of headers is list.

    import urllib2
    import cookielib
    
    class dummyResponse:
        def __init__(self,headers):
            self.headers=headers
        def info(self):
            return dummyInfo(self.headers)
    
    class dummyInfo:
        def __init__(self,headers):
            self.headers=headers
        def getheaders(self,key):
            #Headers are in the form: 'Set-Cookie: key=val\r\n'. We want 'key=val'
            newMatches=[]
            for header in self.headers:
                if header.lower().startswith(key.lower()):
                    clearHeader=header[len(key)+1:].strip()
                    newMatches.append(clearHeader)
            return newMatches
    
    req=urllib2.Request(url)
    resp=dummyResponse(headers)
    
    jar=cookielib.CookieJar()
    jar.extract_cookies(resp, req)
    

提交回复
热议问题