我正在尝试发出一个GET请求,该请求需要在请求标头中包含有效的cookie。
我尝试了以下内容:
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : USERNAME, 'password' : PASSWORD})
opener.open("SERVER_URL, login_data)
resp = opener.open(ORDER_URL)
print resp.read()
它为我提供了登录页面的HTML响应。
也尝试过:
from requests import session
payload = {
'action': 'login',
'username': USERNAME,
'password': PASSWORD
}
with session() as c:
c.post(SERVER_URL, data=payload)
request = c.get(ORDER_URL)
print request.headers
print request.text
它为我提供了登录页面的HTML响应。
也尝试过:
import urllib2
import urllib
from cookielib import CookieJar
cj = CookieJar()
p = urllib2.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, SERVER_URL, USERNAME, PASSWORD)
handler = urllib2.HTTPBasicAuthHandler(p)
opener = urllib2.build_opener(*[urllib2.HTTPCookieProcessor(cj), urllib2.HTTPBasicAuthHandler(p)])
urllib2.install_opener(opener)
response2 = opener.open(ORDER_URL)
print response2.read()
但仍然是HTML响应
如果我在登录后从我的浏览器复制cookie并执行以下操作,那么我得到正确的答复:
req = urllib2.Request(ORDER_URL)
req.add_header("Cookie", cookie)
pdb.set_trace()
response = urllib2.urlopen(req)
print response.read()
如何使用python正确设置cookie?
初始登录请求提供以下响应标头:
CaseInsensitiveDict({'content-encoding': 'gzip', 'transfer-encoding': 'chunked',
'x-powered-by': 'Express', 'server': 'nginx/1.4.4', 'connection': 'keep-alive',
'date': 'Tue, 09 Dec 2014 10:51:46 GMT',
'x-frame-options': 'SAMEORIGIN', 'content-type': 'text/html; charset=utf-8'})