urllib常用小记

urllib简介

python3内置库urllib,包含一系列处理URL的方法。urllib有四个子模块:

  • urllib.request
  • urllib.error
  • urllib.parse
  • urllib.robotparser

urllib.request

这个模块最重要内容是方法urllib.request.urlopen()与URL请求类urllib.request.Request()

方法:urllib.request.urlopen

方法定义为:

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

参数url是一个str对象或者Request对象。如果是字符串对象,其值是有效的URL;Request对象由一个抽象的请求类urllib.request.Request()实例化,如果我们要定制请求头或者发起POST请求,把Request对象作为参数更适合。

如果发起POST请求,我们就要传入data参数,该参数是一个bytes、file-like或iterables(可迭代对象)。它最常见的形式为将要查询的键值对通过urllib.parse.urlencode编码为application/x-www-form-urlencoded格式(注意这是一个str对象),然后编码为bytes对象,赋给data参数。

该方法返回值对象有三个通用方法:

  • geturl()
  • info()
  • getcode()

如果URL是HTTP或HTTPS协议,那么返回对象会继承http.client.HTTPResponse对象的方法和属性:

  • HTTPResponse.read([amt])
  • HTTPResponse.getheader(name, default=None)
  • HTTPResponse.msg
  • HTTPResponse.version
  • HTTPResponse.status
  • HTTPResponse.reason

它的返回值还有上下文管理器特性,这意味我们可以使用with ··· as语句

类:urllib.request.Request

类定义为:

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

参数url是一个str对象,其值是有效的URL;参数method默认或者data=None时,值为GET,否则值为POST

urllib.request.urlopen()一样,data参数一般需要urllib.parse.urlencode编码,然后再编码为bytes对象。

headers是个字典对象,可以定制请求头。如果业务场景是爬虫,User-Agent默认值为Python-urllib/2.6,我们通常不使用这个默认的用户代理。

实例化对象的常用方法和属性如下:

  • Request.type
  • Request.origin_req_host
  • Request.selector
  • Request.data
  • Request.get_full_url()
  • Request.unverifiable
  • Request.method
  • Request.get_method()
  • Request.add_header(key, val)
  • Request.add_unredirected_header(key, header)
  • Request.has_header(header)
  • Request.remove_header(header)
  • Request.get_header(header_name, default=None)
  • Request.header_items()
  • Request.set_proxy(host, type)

代理

首先,通过urllib.request.ProxyHandler(proxies=None)实例化handlers对象,它包含了协议和代理服务器的IP及端口;然后使用urllib.request.build_opener([handler, ...])方法构建OpenerDirector对象,通过它,利用OpenerDirector.open()方法打开URL。

如果我们要使用全局代理,需要OpenerDirector对象传入urllib.request.install_opener(opener),此后urlopen()都通过OpenerDirector打开URL。

方法:urllib.request.urlretrieve

方法定义为:

urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)

该方法可以将URL表示的网络对象下载到本地文件,它还返回一个两元素元组(filename, headers)filename是本地文件名,headers是响应头。

当参数filename未指定,会自动创建临时文件。

reporthook是回调函数,该函数接受三个参数:目前已下载块的数量、每个块的大小(字节表示)、文件的总大小;当首次链接到URL时会触发一次回调函数,此后每读取一个块,触发一次回调函数。

当HTTP协议时,可以发起POST请求,同urllib.request.urlopen()一样,data参数一般需要urllib.parse.urlencode编码,然后再编码为bytes对象。

读取下载的文件时,如果出现unicode错误,可以尝试指定打开文件的编码为utf-8

urllib.parse

这个模块比较常用的方法是urllib.parse.urlencode,用于对查询键值对编码为application/x-www-form-urlencoded格式。

该方法定义为:

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus)

参数query是一个dict对象或含有两元素的元组的列表对象。

返回值是ascii编码的str对象。

代码示例如下:

  • GET请求

    import urllib.request
    import urllib.parse
    params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
    url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
    with urllib.request.urlopen(url) as f:
        print(f.read().decode('utf-8'))
    
  • POST请求

    import urllib.request
    import urllib.parse
    data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
    data = data.encode('ascii')
    with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
        print(f.read().decode('utf-8'))
    

urllib.error

这个模块定义了异常对象urllib.error.URLErrorurllib.error.HTTPError

这两个异常对象有不同的属性。

  • urllib.error.URLError
    • reason
  • urllib.error.HTTPError
    • reason
    • code
    • headers

urllib.robotparser

这个模块式用来解析robots.txt,通过urllib.robotparser.RobotFileParser对象操作robots.txt文件。

类定义如下:

urllib.robotparser.RobotFileParser(url='')

常用方法和属性如下:

  • set_url(url)
  • read()
  • can_fetch(useragent, url)
  • crawl_delay(useragent)
  • request_rate(useragent)
原文地址:https://www.cnblogs.com/weixia-blog/p/9124111.html