我尝试使用HTTPResponse
从cookielib.CookieJar.extract_cookies()
中提取Cookie,但我一直收到一条错误消息,指出响应对象没有.info
属性。我知道它更适用于urllib2.urlopen
返回的伪文件对象,但是从HTTPResponse
提取cookie的规范方法是什么?这就是我所拥有的:
def _make_request(self, loc, headers, data=None, retry=True):
retries = 0
max_retries = self._retry_max if retry else 1
self._request = urllib2.Request('http://example.com/')
self._connection = httplib.HTTPSConnection(host)
try:
while retries < max_retries:
try:
self._request.add_data(data)
self._connection.request(self._request.get_method(), self._request.get_selector() + loc,
self._request.get_data(), headers)
resp = self._connection.getresponse()
self._cookies.extract_cookies(resp, self._request) # problems!
if len(self._cookies) > 0:
# do something
...
由于
答案 0 :(得分:0)
尝试使用密钥set-cookie
来获取Cookie。这是你的例子。
#!/usr/bin/env python
import urllib
import httplib2
http = httplib2.Http()
url = 'http://www.example.com/login'
body = {'USERNAME': 'foo', 'PASSWORD': 'bar'}
headers = {'Content-type': 'application/x-www-form-urlencoded'}
response, content = http.request(url, 'POST', headers=headers, body=urllib.urlencode(body))
headers = {'Cookie': response['set-cookie']}
url = 'http://www.example.com/home'
response, content = http.request(url, 'GET', headers=headers)