Python3爬虫一之(urllib库)

urllib库是python3的内置HTTP请求库。html

ython2中urllib分为 urllib二、urllib两个库来发送请求,可是在python3中只有一个urllib库,方便了许多。python

urllib库官方文档地址:https://docs.python.org/3/library/urllib.html网站

urllib库包含四个模块:编码

  request: 最基本的request请求模块,用来模拟的发送请求url

  error: 异常处理模块用来捕获异常spa

  parse: 提供了许多URL处理方法,好比拆分、解析、合并debug

  robotparser: 用来识别网站的robot.txt文件代理

发送请求:request下的urlopen()方法code

import urllib.request
url = 'http://xa.meituan.com/meishi/'
response = urllib.request.urlopen(url)
print(response.read().decode())

获得的response是一个HTTPResponse类型的对象,包含了 read(), readinto(), getheader(name), getheaders(), fileno()等方法和msg, version, status, debuglevel, closed等属性。htm

使用urlopen()方法是也能够传递一些参数,如data, timeout 等

data参数:

  data是可选参数,若是在请求中想要添加data参数, data参数必须用bytes()将其转化为bytes类型,而且,若是传递了参数,那么请求方式就是POST类型(urlopen请求方式默认是get)

import urllib.request
import urllib.parse
data = bytes(urllib.parse.urlencode({'world':'Hello'}), encoding='utf-8')
#传递一个data字典,使用bytes方法将data转为bytes类型,bytes方法的第一个参数是str,因此使用urllib.parse.urlencode()方法将字典转为str,第二个参数是编码格式
url = 'http://xa.meituan.com/meishi/'
response = urllib.request.urlopen(url=url, data=data)
print(response.read().decode())

timeout参数:

  该参数用于设定超时时间。单位是秒。超时就会抛出异常。

import urllib.request
url = 'http://xa.meituan.com/meishi/'
response = urllib.request.urlopen(url=url, timeout=1)
print(response.read().decode())

其余参数: 

  context参数, 必须是ssl.SSLCentext类型, 用来指定SSL设置。

  cafile参数和capath参数分别指定CA证书与他的路径。

 

request下的Request方法:

Request的构造方法:

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

import urllib.request
url = 'http://xa.meituan.com/meishi/'
request = urllib.request.Request(url=url)
response = urllib.request.urlopen(request)
print(response.read().decode())

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

unverifiable:表示这个请求是不是没法验证的,默认是False,意思是

 

Handler

urllib,request.BaseHandler类。他是全部Handler的父类。

下面各类子类继承父类。

  HTTPDefaultErrorHandler: 用于处理HTTP请求

  HTTPRedirectHandler: 用于重定向。

  HTTP Cookie Processor:用于处理Cookies

  ProxyHandler:用于设置代理。

  HTTPPasswordMgr:用于管理密码。

  HTTPBasicAuthHandler: 用于认证管理。

URL:  scheme + netloc + path +    parms + query + fragment

            协议         域名   访问路径   参数    查询条件     锚点