将`Cookie`放在`CookieJar`中

时间:2011-07-29 20:02:17

标签: python cookies http-request python-requests

我正在使用新的Python Requests库来发出http请求。我从服务器获取cookie作为文本。如何将其转换为包含Cookie的CookieJar

10 个答案:

答案 0 :(得分:46)

我对这个问题感到困惑。请求库会将cookie放入jar中。

import requests
import cookielib


URL = '...whatever...'
jar = cookielib.CookieJar()
r = requests.get(URL, cookies=jar)
r = requests.get(URL, cookies=jar)

对URL的第一个请求将填充jar。第二个请求将cookie发送回服务器。标准库的urllib模块cookielib也是如此。 (doc目前可用于2.x版本)

答案 1 :(得分:23)

请求Session也会收到并发送Cookie。

s = requests.Session()

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")

print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'

(上述代码来自http://www.python-requests.org/en/latest/user/advanced/#session-objects

如果您希望在代码运行之间将cookie保留在磁盘上,您可以直接使用cookie jar并保存/加载它们。更麻烦,但仍然很容易:

import requests
import cookielib

cookie_file = '/tmp/cookies'
cj = cookielib.LWPCookieJar(cookie_file)

# Load existing cookies (file might not yet exist)
try:
    cj.load()
except:
    pass

s = requests.Session()
s.cookies = cj

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")

# Save cookies to disk, even session cookies
cj.save(ignore_discard=True)

然后查看文件:

$ cat /tmp/cookies 
#LWP-Cookies-2.0
Set-Cookie3: sessioncookie=123456789; path="/"; domain="httpbin.org"; path_spec; discard; version=0

答案 2 :(得分:4)

为了帮助你,我写了一个完整的模块。我尝试使用我的个人网页和谷歌的cookie,所以我认为它有效。

我从How to add cookie to existing cookielib CookieJar instance in Python?获得了帮助

我在这里有很多untythonic代码,包括半kludge,所以你的里程可能会有所不同。根据需要调整它,特别是对于假定的项目(例如端口80),下面的“request”作为参数类型为requests.request,我意识到“method”参数必须是所有大写字母。希望我能帮忙!

注意:我没有时间添加注释以便澄清,因此您必须使用源代码。

import Cookie,cookielib,requests,datetime,time  #had this out but realized later I needed it when I continued testing

def time_to_tuple(time_string):
    wday = {'Mon':0,'Tue':1,'Wed':2,'Thu':3,'Fri':4,'Sat':5,'Sun':6}
    mon = {'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12}
    info = time_string.split(' ')
    info = [i.strip() for i in info if type(i)==str]
    month = None
    for i in info:
        if '-' in i:
            tmp = i.split('-')
            for m in tmp:
                try:
                    tmp2 = int(m)
                    if tmp2<31:
                        mday = tmp2
                    elif tmp2 > 2000:
                        year = tmp2
                except:
                    for key in mon:
                        if m.lower() in key.lower():
                            month = mon[key]
        elif ':' in i:
            tmp = i.split(':')
            if len(tmp)==2:
                hour = int(tmp[0])
                minute = int(tmp[1])
            if len(tmp)==3:
                hour = int(tmp[0])
                minute = int(tmp[1])
                second = int(tmp[2])
        else:
            for item in wday:
                if ((i.lower() in item.lower()) or (item.lower() in i.lower())):
                    day = wday[item]
            if month is None:
                for item in mon:
                    if ((i.lower() in item.lower()) or (item.lower() in i.lower())):
                        month = mon[item]
    return year,month,mday,hour,minute,second

def timefrom(year,month,mday,hour,minute,second):
    time_now = time.gmtime()
    datetime_now = datetime.datetime(time_now.tm_year,time_now.tm_mon,
                                     time_now.tm_mday,time_now.tm_hour,
                                     time_now.tm_min,time_now.tm_sec)
    then = datetime.datetime(year,month,mday,hour,minute,second)
    return (datetime_now-then).total_seconds()

def timeto(year,month,mday,hour,minute,second):
    return -1*timefrom(year,month,mday,hour,minute,second)



##['comment', 'domain', 'secure', 'expires', 'max-age', 'version', 'path', 'httponly']
def parse_request(request):
    headers = request.headers
    cookieinfo = headers['set-cookie'].split(';')
    name = 'Undefined'
    port=80
    port_specified=True
    c = Cookie.SmartCookie(headers['set-cookie'])
    cj = cookielib.CookieJar()
    for m in c.values():
        value = m.coded_value
        domain = m['domain']
        expires = m['expires']
        if type(expires) == str:
            tmp = time_to_tuple(expires)
            expires = timeto(tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5])
        max_age=m['max-age']
        version = m['version']
        if version == '':
            version = 0
        path = m['path']
        httponly = m['httponly']
        if httponly == '':
            if 'httponly' in headers['set-cookie'].lower():
                httponly = True
        else:
            httponly = False
        secure = m['secure']
        comment=m['comment']
        port = 80
        port_specified=False
        domain_specified=True
        domain_initial_dot = domain.startswith('.')
        path_specified=True
        discard = True
        comment_url=None
        rest={'HttpOnly':httponly}
        rfc2109=False
        ck = cookielib.Cookie(version,name,value,port,port_specified,domain,
                              domain_specified,domain_initial_dot,path,path_specified,
                              secure,expires,discard,comment,comment_url,rest,rfc2109)
        cj.set_cookie(ck)
    return cj

答案 3 :(得分:3)

well cookielib.LWPCookieJar上有加载和保存方法。查看格式并查看它是否与本机cookie格式匹配,您可以使用StringIO将cookie直接加载到cookie jar中。或者,如果请求在引擎盖下使用urllib2,你不能在默认的开启者中添加一个cookie处理程序吗?

答案 4 :(得分:3)

我认为很多这些答案都没有提到。有时,其他图书馆并未使用引擎下的请求。或者不会暴露它使用的cookiejar。有时我们所有是cookie字符串。在我的情况下,我试图从pyVmomi借用auth cookie。

import requests
import http.cookies
raw_cookie_line = 'foo="a secret value"; Path=/; HttpOnly; Secure; '
simple_cookie = http.cookies.SimpleCookie(raw_cookie_line)
cookie_jar = requests.cookies.RequestsCookieJar()
cookie_jar.update(simple_cookie)

这为我们提供了以下cookie_jar

In [5]: cookie_jar
Out[5]: <RequestsCookieJar[Cookie(version=0, name='foo', value='a secret value', port=None, port_specified=False, domain='', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=True, expires=None, discard=False, comment='', comment_url=False, rest={'HttpOnly': True}, rfc2109=False)]>

我们可以正常使用:

requests.get(..., cookies=cookie_jar)

答案 5 :(得分:2)

我正在尝试做同样的事情。这是我到目前为止,由于某种原因,它不是在标题中发送cookie。它可能会帮助你解决问题。

import requests
import cookielib
import logging

log = logging.getLogger(__name__)

def auth(auth_url, cookies):
    cj = cookielib.CookieJar()
    for x in cookies:
         if len(cookies[x]) > 0:
             ck = cookielib.Cookie(version=1, name=x, value=cookies[x], 
                    port=None, port_specified=False, domain='.example.com', 
                    domain_specified=True, 
                    domain_initial_dot=True, path='/', 
                    path_specified=True, secure=False, 
                    expires=None, discard=True, 
                    comment=None, comment_url=None, 
                    rest=None, rfc2109=True)
             log.info(ck)
             cj.set_cookie(ck)

    log.info("cookies = %s " % cj)
    response = requests.get(auth_url, cookies=cj)
    log.info("response %s \n" % response)
    log.info("response.headers %s \n" % response.headers)
    log.info("response.content %s \n" % response.content)

答案 6 :(得分:2)

假设您已请求url并获得headers作为回复。类型类型url是字符串。类型类型headers是列表。

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)

答案 7 :(得分:1)

试试这个网站:Voidspace article

多年来,我发现空隙对于做这种事情非常有用。希望我帮助过,虽然我很笨。该代码位于Voidspace Recipes 作为源代码.py虽然下载文件是&#34; .py - &#34;文件。

答案 8 :(得分:1)

作为dstanek answered,请求会自动将响应cookie放入cookie罐中 但是,如果您手动指定Cookie标头条目,请求将不会将这些Cookie放入jar中。这意味着任何后续请求都将缺少您的初始cookie集,但将会有任何新的cookie。

如果您确实需要为请求手动创建Cookie jar,请使用requests.cookies.RequestsCookieJar。如果他们的示例代码发生了变化:

jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum',   domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=jar)

请注意,如果您提供Cookie jar Cookie标头,则标头优先,但仍会保留Cookie jar以供将来请求使用。

答案 9 :(得分:1)

关于如何获取cookiejar并将cookie保留在Python3中的思考的简化版本:

import requests

s = requests.Session()

r1 = s.get('https://stackoverflow.com')
print("r1",r1.cookies) #Have cookie
print("s",s.cookies)  #Have cookie(jar)

r2 = s.get('https://stackoverflow.com') #The cookie from r1 is resend
print("r2",r2.cookies) #No cookie (could be a new one)
print("s",s.cookies)  #Keep the cookie(jar) from r1

要在会话之间保留cookie,您必须保存并重用Session中的cookiejar( s 变量)。 如果在其他站点的r1 / r2 / s之间得到不同的答案,请检查是否存在重定向。例如,r1 / r2将不会获得https://www.stackoverflow.com的cookie,因为它将被重定向到没有www的站点。