简体   繁体   English

通过urllib2 python发送/设置cookie

[英]send/set cookie via urllib2 python

I am quite new to python and I am rather struck for a couple of days now trying to send a cookie with urllib2. 我是python的新手,现在尝试发送urllib2的cookie令我有些震惊。 So, basically, on the page I want to get, I see from firebug that there is a "sent cookie" which looks like: 因此,基本上,在我要获取的页面上,我从萤火虫中看到有一个“已发送的cookie”,看起来像:

 list_type=height

.. which basically arranges the list on the page in a certain order. ..基本上按一定顺序在页面上排列列表。

I would like to send this above cookie info via urllib2, so that the rendered page taked this above setting into effect - and here is the code I am trying to write to make it work: 我想通过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()

..as you can see, I have tried a couple of things: ..如您所见,我已经尝试了几件事:

  • setting the parameter via a header 通过标题设置参数
  • setting a cookie 设置一个cookie

however, these do not seem to render the page in the certain list_order (height) as I would like. 但是,这些似乎并没有按照我希望的那样以特定的list_order(高度)呈现页面。 I was wondering if someone could point me in the right direction as to how to send the cookie information with urllib2 我想知道是否有人可以向我指出有关如何使用urllib2发送cookie信息的正确方向

Thanks. 谢谢。

An easy way to generate a cookie.txt is this chrome extension: https://chrome.google.com/webstore/detail/cookietxt-export/lopabhfecdfhgogdbojmaicoicjekelh chrome扩展程序是生成cookie.txt的一种简单方法: 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)

[update] [更新]

Sorry, I was pasting from an old code snippet long forgotten. 抱歉,我正在粘贴一个久已忘记的旧代码片段。 From the LWPCookieJar docstring: 从LWPCookieJar文档字符串:

The LWPCookieJar saves a sequence of "Set-Cookie3" lines. LWPCookieJar保存“ Set-Cookie3”行的序列。 "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. “ Set-Cookie3”是libwww-perl库所使用的格式,未知与任何浏览器都兼容,但易于阅读且不会丢失有关RFC 2965 cookie的信息。

So it is not compatible with the cookie.txt generated by modern browsers. 因此,它与现代浏览器生成的cookie.txt不兼容。 If you try to load it with you will get: LoadError: 'cookies.txt' does not look like a Set-Cookie3 (LWP) format file . 如果尝试使用它加载,则会得到: LoadError: 'cookies.txt' does not look like a Set-Cookie3 (LWP) format file

You can do as the OP and convert the file: 您可以作为OP并转换文件:

there is something wrong with the format of the output from chrome extension. chrome扩展程序的输出格式有问题。 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. 我只是搜索了lwp问题,发现:code.activestate.com/recipes/302930-cookielib-example该代码以lwp格式吐出cookie,然后按原样执行您的步骤。 - James W - 詹姆斯·W

You can also use this Firefox addon , and then "Tools->Export cookies". 您也可以使用此Firefox插件 ,然后使用“工具”->“导出cookie”。 Make sure the first line in the cookies.txt file is "# Netscape HTTP Cookie File" and use: 确保cookies.txt文件中的第一行是“#Netscape HTTP Cookie文件”,并使用:

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

You would better look into the 'request' module for Python making HTTP much easier approachable than through the low-level urllib modules. 您最好查看Python的“请求”模块,从而使HTTP比通过低级urllib模块更容易实现。

See 看到

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

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

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