python3的urllib库

首先要了解一下什么是Urllib 库,它是 Python 内置的 HTTP 请求库,它包含四个模块:

  • 第一个模块 request,它是最基本的 HTTP 请求模块,我们可以用它来模拟发送一请求,就像在浏览器里输入网址然后敲击回车一样,只需要给库方法传入 URL 还有额外的参数,就可以模拟实现这个过程了。
  • 第二个 error 模块即异常处理模块,如果出现请求错误,我们可以捕获这些异常,然后进行重试或其他操作保证程序不会意外终止。
  • 第三个 parse 模块是一个工具模块,提供了许多 URL 处理方法,比如拆分、解析、合并等等的方法。
  • 第四个模块是 robotparser,主要是用来识别网站的 robots.txt 文件,然后判断哪些网站可以爬,哪些网站不可以爬的,其实用的比较少。

下面讲解一下常用的模块及其中的函数:

  • urllib.request 模块定义了适用于在各种复杂情况下打开 URL(主要为 HTTP)的函数和类 --- 例如基本认证、摘要认证、重定向、cookies 及其它。
  • urllib.request 模块中主要的函数:
    • urllib.request.urlopen(url,data=None,[timeout,],cafile=None,capath=None,cadefault=False,context=None)

       请求对象,返回一个HTTPResponse类型的对象,包含的方法和属性:

       方法:read()、readinto()、getheader(name)、getheaders()、fileno()

       属性:msg、version、status、reason、bebuglevel、closed

    • urllib.request.Request(url,data=None,headers={},origin_req_host=None,unverifiable=False,method=None)

      参数:

      url:请求的URL,必须传递的参数,其他都是可选参数

      data:上传的数据,必须传bytes字节流类型的数据,如果它是字典,可以先用urllib.parse模块里的urlencode()编码

      headers:它是一个字典,传递的是请求头数据,可以通过它构造请求头,也可以通过调用请求实例的方法add_header()来添加

      origin_req_host:指请求方的host名称或者IP地址

      unverifiable:表示这个请求是否是无法验证的,默认为False,如我们请求一张图片如果没有权限获取图片那它的值就是true

      method:是一个字符串,用来指示请求使用的方法,如:GET,POST,PUT等

    • 示例
  • urllib.error 模块为 urllib.request 所引发的异常定义了异常类模块。 基础异常类是 URLError
    • urllib.request 出现异常时引发
  • urllib.parse为url解析模块。

    • urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True),拆分URL

       

       

      • from urllib.parse import urlparse
        o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
        print(o)
        
        ParseResult(scheme='http', netloc='www.cwi.nl:80',path='/%7Eguido/Python.html',
                    params='', query='', fragment='')
    • urllib.parse.quote(string, safe='/', encoding=None, errors=None) ,对一些非ASCii符号编码
      •  str = 'key = 武汉加油'
         encodestr = urllib.parse.quote(str)
         print(encodestr)
        
        key%20%3D%20%E6%AD%A6%E6%B1%89%E5%8A%A0%E6%B2%B9
        
        
        str = 'key = 武汉加油'
        encodestr = urllib.parse.quote(str,safe='= ')
        print(encodestr)
        
        key = %E6%AD%A6%E6%B1%89%E5%8A%A0%E6%B2%B9
    • urllib.parse.unquote(string, encoding='utf-8', errors='replace'),对url进行解码
      • str = 'key = %E6%AD%A6%E6%B1%89%E5%8A%A0%E6%B2%B9'
        encodestr = urllib.parse.unquote(str)
        print(encodestr)
        
        key = 武汉加油

urllib.parse.quote(string, safe='/', encoding=None, errors=None)

原文地址:https://www.cnblogs.com/KYin/p/12488192.html