如何使用Python 2.7和Requests保存Netscape样式的cookies.txt文件?

时间:2013-05-16 17:50:16

标签: python-2.7 python-requests cookielib cookiejar

我正在使用请求来获取网页,我想将cookie保存在Netscape风格的cookies.txt文件中。我怎样才能做到这一点?我尝试过以下方法:

import requests
import cookielib

url = 'http://www.yahoo.com'
ua = ("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) "
      "Gecko/20100101 Firefox/21.0")
headers = {'user-agent': ua}

mcj = cookielib.MozillaCookieJar()
requests.get(url, headers=headers, cookies=mcj)
mcj.save('cookies.txt')
print open('cookies.txt').read()

但它只创建一个没有cookie的cookie文件,因此输出为:

# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file!  Do not edit.

1 个答案:

答案 0 :(得分:-1)

服务器发送的cookie位于响应对象的cookies属性中;请参阅requests.Response课程的documentation