这里写目录标题
一,urllib四大模块
1,request:基本的HTTP请求模块,可以用来模拟发送请求。
2,error:异常处理模块。
3,parse:工具模块,提供URL处理方法。
4,robotparse:识别网站的robot.txt文件,判断该网站是否可以爬。
二,发送请求
Ⅰ:urlopen的使用
- 作用
抓取网页源代码。 - 使用方法
import urllib.request
response = urllib.request.urlopen('https://www.baidu.com/')
print(response.read().decode('utf-8'))
程序将输出百度首页的源代码。
-
返回
返回一个HTTPResponse类型的对象。 -
方法和属性
该类型包含的方法:
read():用于输出源代码
getheader(name):输出特定响应的头信息
getheaders():输出全部相应的头信息
该类型包含的属性:
status:可得到返回结果的状态码 -
decode和encode:
decode encode
str ---------> str(Unicode) ---------> str
//unicode 为一种编码格式
6,参数
data:
用于模拟表单提交,以POST方式传输数据。
timeout:
设置超时时间,单位为秒。
如果超过设定的时间,将抛出异常。
Ⅱ:Request的使用
urlopen无法构建一个完整的请求,借助Request能使请求更完整。
1,构造
class urllib.request.Request(url,data=None,headers={
},origin_req_host=None,unverifiable=False,method=None)
2,参数解析
url:
用于请求URL,必传参数。
data:
headers:
是一个字典,请求头。可以在构造请求时直接对headers赋值,也可用add_headers()方法来添加。
常常通过修改User-Agent来伪装浏览器。
origin_req_host:
unverifiable:
method:
字符串,用来指示请求的方法,如GET、POST和PUT。
3,实例
import urllib.request
header = {
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36'}
request = urllib.request.Request('https://www.baidu.com/',headers=header,method='GET')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
Ⅲ:Handler
处理器,可用于处理登陆验证,Cookies,代理设置等。
1,Handler类
BaseHandler:是其他Handler的父类。
HTTPDefaultErrorHandler:
HTTPRedirectHandler:
HTTPCookieProcessor:用于处理Cookies。
ProxyHa