在Python中获取所有Cookie

20 投票
4 回答
45631 浏览
提问于 2025-04-15 11:53

我该如何在Python中读取所有的cookie,而不需要知道它们的名字呢?

4 个回答

5

这可能正是你所需要的。

Python 3.4

import requests

r = requests.get('http://www.about.com/')
c = r.cookies
i = c.items()

for name, value in i:
    print(name, value)
6

os.environ['HTTP_COOKIE'] 放进一个数组里:

#!/usr/bin/env python

import os

 if 'HTTP_COOKIE' in os.environ:
  cookies = os.environ['HTTP_COOKIE']
  cookies = cookies.split('; ')
  handler = {}

  for cookie in cookies:
   cookie = cookie.split('=')
   handler[cookie[0]] = cookie[1]
24

不太确定这是不是你想要的,不过这里有个简单的例子,教你怎么把饼干放进饼干罐里,然后再把它们拿出来:

from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import cookielib

#Create a CookieJar object to hold the cookies
cj = cookielib.CookieJar()
#Create an opener to open pages using the http protocol and to process cookies.
opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler())

#create a request object to be used to get the page.
req = Request("http://www.about.com")
f = opener.open(req)

#see the first few lines of the page
html = f.read()
print html[:50]

#Check out the cookies
print "the cookies are: "
for cookie in cj:
    print cookie

撰写回答