zoukankan      html  css  js  c++  java
  • urllib2模块、cookielib模块

                                                                    urllib2模块

          urllib模块和urllib模块类似,用来打开URL并从中获取数据。与urllib模块不同的是,urllib模块不仅可以使用urlopen() 函数还可以自定义Opener来访问网页。同时要注意:urlretrieve()函数是urllib模块中的,urllib2模块中不存在该函数。但是 使用urllib2模块时一般都离不开urllib模块,因为POST的数据需要使用urllib.urlencode()函数来编码。

          一、urlopen()

                最简单的请求方式就是用urlopen()函数。

                urlopen (url [,data ,[timeout]]) 函数打开URL url并返回类文件对象,使用该对象可以读取返回的内容。其中,参数url 可以是包含URL的字符串,也可以是urllib2.Request类的实例。data是经过编码的POST数据(一般使用 urllib.urlencode()来编码)。timeout是可选的超时期(以秒为单位),供所有阻塞操作内部使用。

              注意timeout参数,是超时时间,即在中断连接前尝试的时间,但只对HTTP、HTTPS、FTP、FTPS有效。设置超时时间,通过 urlopen()函数设置是最简单的方法,还可以通过socket模块或urllib2模块来设置 (socket.setdefaulttimeout(10)或urllib2.socket.setdefaulttimeout(10))。详细代码 参考《urllib2的使用细节》.

               urlopen()返回的类文件对象u支持一下方法:

     

              对于简单的请求,urlopen()的参数url就是一个代表URL的字符串。但如果需要执行更复杂的操作,如修改HTTP报头,可以创建Request实例并将其作为url参数。

             Request (url [data,headers [,origin_req_host ,[unverifiable]]]])

             Request实例r具有的方法中重要的有以下几个:

           下面代码示例使用Request来更改urlopen()使用的User-Agent报头的方法:

    headers={"User-Agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}
    rq=urllib2.Request("http://www.example.com",headers=headers)
    u=urlopen(rg)

    二、自定义Opener

              基本的urlopen()函数不支持验证、cookie或其他HTTP高级功能。要支持这些功能,必须使用build_opener()函数来创建自己的自定义Opener对象。

              install_opener(opener)  安装opener作为urlopen()使用的全局URL opener,即意味着以后调用urlopen()时都会使用安装的opener对象。opener通常是build_opener()创建的 opener对象。

    复杂情况详细解决办法:

    1、cookie处理

              如果要管理HTTP cookie,需要创建添加了HTTPCookieProcessor处理程序的opener对象。默认情况下。HTTPCookieProcessor 使用CookieJar对象,将不同类型的CookieJar对象作为HTTPCookieProcessor的参数提供,可支持不同的cookie处 理。如下面代码:

    mcj=cookielib.MozillaCookieJar("cookies.txt")
    cookiehand=HTTPCookieProcessor(mcj)
    opener=urllib2.build_opener(cookiehand)
    u=opener.open(http://www.baidu.com)                           

    2、密码验证

    3、代理    

    urllib2会自动检测代理设置,默认使用环境变量http_proxy 来设置 HTTP Proxy通常情况下,这是很有帮助的,因为也可能造成麻烦(因为通过代理获取本地URL资源时会被阻止,因此如果你正在通过代理访问Internet, 那么使用脚本测试本地服务器时必须阻止urllib2模块使用代理)。因此,如果想在程序中明确Proxy的使用而不受环境变量的影响,可以通过创建 ProxyHandler实例,并将实例作为build_opener()的参数来实现。如下面代码:

    import urllib2
     
    enable_proxy = True
    proxy_handler = urllib2.ProxyHandler({"http" : 'http://some-proxy.com:8080'})
    null_proxy_handler = urllib2.ProxyHandler({})
     
    if enable_proxy:
        opener = urllib2.build_opener(proxy_handler)
    else:
        opener = urllib2.build_opener(null_proxy_handler)
     
    urllib2.install_opener(opener)

    cookielib模块

          cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib2模块配合使用来访问Internet资源。例如可以利用本模块 的CookieJar类的对象来捕获cookie并在后续连接请求时重新发送。coiokielib模块用到的对象主要有下面几个:CookieJar、 FileCookieJar、MozillaCookieJar、LWPCookieJar。其中他们的关系如下:

                            CookieJar                       

                                /    

                FileCookieJar      

                 /                       

     MozillaCookieJar      LWPCookieJar            

    1、CookieJar ()

          管理HTTP cookie值、存储HTTP请求生成的cookie、向传出的HTTP请求添加cookie的对象。整个cookie都存储在内存中,对CookieJar实例进行垃圾回收后cookie也将丢失。

          The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses.CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.

    2、FileCookieJar (filename,delayload=None,policy=None)

           创建FileCookieJar实例,检索cookie信息并将cookie存储到文件中。filename是存储cookie的文件名。delayload为True时支持延迟访问访问文件,即只有在需要时才读取文件或在文件中存储数据。

          A CookieJar which can load cookies from, and perhaps save cookies to, a file on disk. Cookies are NOT loaded from the named file until either the load() or revert() method is called.

    3、MozillaCookieJar (filename,delayload=None,policy=None)

          创建与Mozilla浏览器cookies.txt兼容的FileCookieJar实例。

           A FileCookieJar that can load from and save cookies to disk in the Mozilla  cookies.txt  file format (which is also used by the Lynx and Netscape browsers).Also note that cookies saved while Mozilla is running will get clobbered by Mozilla.

    4、LWPCookieJar (filename,delayload=None,policy=None)

          创建与libwww-perl的Set-Cookie3文件格式兼容的FileCookieJar实例。

          A FileCookieJar that can load from and save cookies to disk in format compatible with the libwww-perl library’s Set-Cookie3file format. This is convenient if you want to store cookies in a human-readable file.

      

         除了上面几个函数之外,下面几个函数也很重要:

    FileCookieJar. save ( filename=None ,   ignore_discard=False ,   ignore_expires=False )

    Save cookies to a file.This base class raises NotImplementedError. Subclasses may leave this method unimplemented.filename is the name of file in which to save cookies. If filename is not specified, self.filename is used (whose default is the value passed to the constructor, if any); if self.filename is NoneValueError is raised. ignore_discard: save even cookies set to be discarded. ignore_expires: save even cookies that have expiredThe file is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the load() or revert() methods.

    FileCookieJar. load ( filename=None ,   ignore_discard=False ,   ignore_expires=False )

    Load cookies from a file.Old cookies are kept unless overwritten by newly loaded ones.Arguments are as for save().The named file must be in the format understood by the class, or LoadError will be raised. Also, IOError may be raised, for example if the file does not exist.

    FileCookieJar. revert ( filename=None ,   ignore_discard=False ,   ignore_expires=False )

    Clear all cookies and reload cookies from a saved file. revert() can raise the same exceptions as load(). If there is a failure, the object’s state will not be altered.

    cookielib模块一般与urllib2模块配合使用,主要用在urllib2.build_oper()函数中作为urllib2.HTTPCookieProcessor()的参数。使用方法如下面登录人人网的代码:

    #! /usr/bin/env python
    #coding=utf-8
    import urllib2
    import urllib
    import cookielib
    data={"email":"用户名","password":"密码"}  #登陆用户名和密码
    post_data=urllib.urlencode(data)
    cj=cookielib.CookieJar()
    opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    headers ={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}
    req=urllib2.Request("http://www.renren.com/PLogin.do",post_data,headers)
    content=opener.open(req)
    print content2.read().decode("utf-8").encode("gbk")
  • 相关阅读:
    EXT--columnWidth
    EXT经验--查询items的xtype
    修改VS解决方案及工程名,解决如何打开高/版本VS项目
    jQuery Ajax 全解析(转)
    MS SqlSever一千万条以上记录分页数据库优化经验总结【索引优化 + 代码优化】[转]
    .net框架版本说明
    [Ajax] 使用Ajax异步上传图片文件(非Form表单提交)
    CodeSmith 7.01破解下载
    jQuery插件之Cookie
    Oracle笔记 目录索引
  • 原文地址:https://www.cnblogs.com/mmix2009/p/3226775.html
Copyright © 2011-2022 走看看