[爬虫]3.基本库的使用
使用 urllib
发送请求
urlopen
urllib.request.urlopen(url, data=None, [timeout,]-, cafile=None, capath=None, cadefault=False, context=None)import urllib.request response = urllib.request.urlopen('https://www.python.org') # 获取返回类型 print(type(response)) # 获取返回结果的状态码 print(response.status) # 获取响应头的各数据 print(response.getheaders()) # 获取了响应头中的 Server 值,结果是 nginx,意思是服务器是用 Nginx 搭建的。 print(response.getheader('Server')) #获取读取信息,即网页的源代码 print(response.read().decode('utf-8'))import urllib.parse import urllib.request # 获取hello!xxz,会传送到运行结果的word --POST模拟表单获取 # urlencode 方法来将参数字典转化为字符串 data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8') response = urllib.request.urlopen('http://httpbin.org/post', data=data) print(response.read())import socket import urllib.request import urllib.error try: response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1) except urllib.error.URLError as e: # socket.timeout --超时异常 if isinstance(e.reason, socket.timeout): print('TIME OUT')
Requset[power!]
power!
处理异常
URLError
HTTPError
结合使用
解析链接
urlparse -解析URL
urlunparse -构造URL
urlsplit -解析URL
urlunsplit -构造URL
urljoin -解析URL
urlencode -转GET请求参数
parse_qs -转字典
parse_qsl -转元组
quote -URL 编码
unquote --URL 解码
分析Robots
Robots 协议
爬虫名称
爬虫名称
名 称
网 站
robotparser
request和urllib的区别
使用 requests
基本用法
GET请求方法:
其他请求方法:
响应
高级用法
文件上传
cookies
会话维持
SSL 证书验证
代理设置
超时设置
身份认证
Prepared Request
正则表达式
常用的匹配规则
模 式
描 述
match :从头找
匹配目标
通用匹配(./*)
贪婪与非贪婪
修饰符
修饰符
描 述
转义匹配 \
search :找一个
findall :找全部
sub :删除
compile :复用
方法技巧
案例:抓取猫眼电影排行
目标
分析
开始写代码
最后更新于
