通过urllib2 python发送/设置cookie

2024-03-29 09:42:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python还不太熟悉,有几天我很震惊,现在我想用urllib2发送一个cookie。所以,基本上,在我想要得到的页面上,我从firebug看到有一个“sent cookie”,看起来像:

 list_type=height

。。它基本上是按一定的顺序排列页面上的列表。

我想通过urllib2发送上述cookie信息,以便呈现的页面将上述设置生效-下面是我试图编写的代码,以使其正常工作:

class Networksx(object):
    def __init__(self):
        self.cj = cookielib.CookieJar()
        self.opener = urllib2.build_opener\
                #socks handler
        self.opener.addheaders = [
        ('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13'),
        ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'),
        ('Keep-Alive', '115'),
        ('Connection', 'keep-alive'),
        ('Cache-Control', 'max-age=0'),
        ('Referer', 'http://www.google.com'),
        ("Cookie", {"list_type":"height"}),
    ]
    urllib2.install_opener(self.opener)
    self.params = { 'Set-Cookie': "list_type":"height"}
    self.encoded_params = urllib.urlencode( self.params )

    def fullinfo(self,url):
        return self.opener.open(url,self.encoded_params).read()

……如你所见,我试过几件事:

  • 通过头设置参数
  • 设置cookie

但是,这些似乎并不像我所希望的那样以特定的列表顺序(高度)呈现页面。我想知道是否有人能给我指出正确的方向,告诉我如何用urllib2发送cookie信息

谢谢。


Tags: self信息列表cookiewindowsdeftype页面
2条回答

生成cookie.txt的一个简单方法是这个chrome扩展:https://chrome.google.com/webstore/detail/cookietxt-export/lopabhfecdfhgogdbojmaicoicjekelh

import urllib2, cookielib

url = 'https://example.com/path/default.aspx'
txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}

cj = cookielib.LWPCookieJar()
# cj.load signature: filename=None, ignore_discard=False, ignore_expires=False
cj.load('/path/to/my/cookies.txt') 

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

req = urllib2.Request(url, None, txheaders)
handle = urllib2.urlopen(req)

[更新]

对不起,我粘贴的是一段被遗忘已久的旧代码片段。从LWPCookieJar文档字符串:

The LWPCookieJar saves a sequence of "Set-Cookie3" lines. "Set-Cookie3" is the format used by the libwww-perl libary, not known to be compatible with any browser, but which is easy to read and doesn't lose information about RFC 2965 cookies.

因此它与现代浏览器生成的cookie.txt不兼容。如果您尝试加载它,您将得到:LoadError: 'cookies.txt' does not look like a Set-Cookie3 (LWP) format file

您可以作为OP执行以下操作并转换文件:

there is something wrong with the format of the output from chrome extension. I just googled the lwp problem and found: code.activestate.com/recipes/302930-cookielib-example the code spits out the cookie in lwp format and then I follow your steps as it is. - James W

您还可以使用这个Firefox addon,然后使用“工具->;导出cookies”。确保cookies.txt文件中的第一行是“#Netscape HTTP Cookie文件”,并使用:

cj = cookielib.MozillaCookieJar('/path/to/my/cookies.txt')
cj.load() 

您最好查看Python的“request”模块,使HTTP比通过低级urllib模块更容易访问。

http://docs.python-requests.org/en/latest/user/quickstart/#cookies

相关问题 更多 >