简体   繁体   English

如何在urllib2中手动设置Cookie?

[英]How to set Cookie in urllib2 manually?

I am using python urllib2 to download web pages. 我正在使用python urllib2下载网页。 But there is a problem that confused me. 但是有一个让我困惑的问题。 I want to set a cookie, but I do not know exactly how to do it. 我想设置一个cookie,但是我不知道该怎么做。 Can I just use CookieJar, or some other way can be tried to solve my problem. 我可以只使用CookieJar,还是可以尝试其他方法来解决我的问题。 Thanks. 谢谢。

Here is my code: 这是我的代码:

def http_get(uri, params, previous_url):
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    urllib2.install_opener(opener)
    opener.handle_open["http"][0].set_http_debuglevel(1)
    user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36'
    opener.addheaders.append(('Cookie','RT=Some Values'))
    opener.addheaders.append(('User-Agent', user_agent))
    opener.addheaders.append(('Referer', previous_url))
    opener.addheaders.append(('Accept', '*/*'))
    opener.addheaders.append(('Accept-Encoding', 'gzip,deflate,sdch'))
    url_values = urllib.urlencode(params)
    request_uri = uri + '?' + url_values    
    request = urllib2.Request(request_uri)
    response = opener.open(request_uri)
    return response, request_uri

I do not know where is wrong, please help! 不知道哪里出了问题,请帮忙!

Did your code works?I think you don't have to use CookieJar.Usually the code should be: 您的代码有效吗?我认为您不必使用CookieJar,通常代码应为:

opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'RT=Some Values'))
#request_uri = ......
response = opener.open(request_uri)
print response.read()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM