爬虫:urllib基本库的使用

urllib包含了request(打开和读取url), error(包含request引发的异常), parse(解析url), robotparser(解析robots.txt文件)四个用于处理URL的模块。

一.发送请求

1.urlopen()

使用urllib.request.urlopen()发送请求:

https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen

发送请求后得到HTTPResponse对象,调用HTTPResponse的相关方法和属性,可以获取相关信息:

https://docs.python.org/3/library/http.client.html#httpresponse-objects

代码示例:

# -*- coding:utf-8 -*-
from urllib import request, error, parse, robotparser
import socket

# get请求
url = 'https://wx.zsxq.com/dweb/#/login'  # 知识星球登录页
res = request.urlopen(url)  # 使用urllib.request模块,发送请求后得到HTTPResponse对象
web_server = res.getheader('Server')  # 查看运行知识星球的服务器类型
print(web_server)   # Tengine(详见http://tengine.taobao.org/)

# post请求
data = bytes(parse.urlencode({'data': '请求的数据'}), encoding='utf-8')  # 使用urllib.parse模块
try:
    res = request.urlopen('https://httpbin.org/post', data=data, timeout=0.01)  # 设置超时时间为0.01s
except error.URLError as e:  # 使用urllib.error模块
    if isinstance(e.reason, socket.timeout):
        print('超时')

2.Request

向urlopen()传递参数并不能构造一个完整的请求对象,所以有了Request Object对象:

https://docs.python.org/3/library/urllib.request.html#request-objects

要构造Request Object对象需要用到urllib.request.Request()方法:

https://docs.python.org/3/library/urllib.request.html#request-objects

代码示例:

# -*- coding:utf-8 -*-
from urllib import request, parse

# 使用urlopen()发起请求时,传入的参数并不能构造一个完整的请求,所以有了urllib.request.Request对象
url = 'https://httpbin.org/post'
data = bytes(parse.urlencode({'data': '请求数据'}), encoding='utf-8')
headers = {
    'Host': 'httpbin.org'
}
req = request.Request(url=url, data=data, headers=headers)
res = request.urlopen(req)
print(res.read().decode('utf-8'))

3.Handler

handler主要用于处理验证,代理 以及Cookies。

(1)验证

(2)代理

(3)Cookies

二.处理异常

三.解析链接

四.分析Robots协议

五.参考资料

[1]崔庆才,《Python3网络开发爬虫实战》

[2]Python官方文档urllib, https://docs.python.org/3/library/urllib.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值