在mooc上学习嵩天老师的爬虫课,整理一些学习笔记~
Requests库的安装
Requests库的安装
Win平台: “以管理员身份运行”cmd,执行pip install requests
这里我要说明的一点是:在我的电脑里同时安装了python2和python3,执行上述语句在python3中会报错,解决方案是执行
pip3 install requests
可以运行如下程序测试Requests库是否成功安装
>>> import requests
>>> r=requests.get("http://www.baidu.com")
>>> print(r.status_code)
200
>>> r.text
u'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden
r.status_code为200表示成功
Requests库的7个主要方法
- requests.request() 构造一个请求,支撑以下各方法的基础方法
- requests.get() 获取HTML网页的主要方法,对应于HTTP的GET
- requests.head() 获取HTML网页头信息的方法,对应于HTTP的HEAD
- requests.post() 向HTML网页提交POST请求的方法,对应于HTTP的POST
- requests.put() 向HTML网页提交PUT请求的方法,对应于HTTP的PUT
- requests.patch() 向HTML网页提交局部修改请求,对应于HTTP的PATCH
- requests.delete() 向HTML页面提交删除请求,对应于HTTP的DELETE
Requests库的get()方法
requests.get()
- url : 拟获取页面的url链接
- params : url中的额外参数,字典或字节流格式,可选
- **kwargs: 12个控制访问的参数
Response对象
Response对象包含服务器返回的所有信息,也包含请求的Request信息
Response对象的属性
- r.status_code HTTP请求的返回状态,200表示连接成功,404表示失败
- r.text HTTP响应内容的字符串形式,即,url对应的页面内容
- r.encoding 从HTTP header中猜测的响应内容编码方式
- r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
- r.content HTTP响应内容的二进制形式
一般会有如下的处理流程
理解Response的编码
- r.encoding 从HTTP header中猜测的响应内容编码方式
- r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
r.encoding:如果header中不存在charset,则认为编码为ISO‐8859‐1
r.text根据r.encoding显示网页内容
r.apparent_encoding:根据网页内容分析出的编码方式
可以看作是r.encoding的备选
爬取网页的通用代码框架
理解Requests库的异常
- requests.ConnectionError 网络连接错误异常,如DNS查询失败、拒绝连接等
- requests.HTTPError HTTP错误异常
- requests.URLRequired URL缺失异常
- requests.TooManyRedirects 超过最大重定向次数,产生重定向异常
- requests.ConnectTimeout 连接远程服务器超时异常
- requests.Timeout 请求URL超时,产生超时异常
r.raise_for_status()方法
- r.raise_for_status() 如果不是200,产生异常requests.HTTPError
增加额外的if语句,该语句便于利用try‐except进行异常处理
爬取网页的通用代码框架
下面是演示例子
HTTP协议及Requests库方法
HTTP协议
HTTP,Hypertext Transfer Protocol,超文本传输协议。HTTP是一个基于“请求与响应”模式的、无状态的应用层协议
HTTP协议采用URL作为定位网络资源的标识,URL格式如下:
port: 端口号,缺省端口为80
path: 请求资源的路径
HTTP URL实例:
http://www.bit.edu.cn
http://220.181.111.188/duty
HTTP URL的理解:
URL是通过HTTP协议存取资源的Internet路径,一个URL对应一个数据资源
HTTP协议对资源的操作
通过URL和命令管理资源,操作独立无状态,网络通道及服务器成为了黑盒子
理解PATCH和PUT的区别
假设URL位置有一组数据UserInfo,包括UserID、UserName等20个字段
需求:用户修改了UserName,其他不变
- 采用PATCH,仅向URL提交UserName的局部更新请求
- 采用PUT,必须将所有20个字段一并提交到URL,未提交字段被删除
HTTP协议与Requests库
HTTP协议方法 Requests库方法 功能一致性
- GET requests.get() 一致
- HEAD requests.head() 一致
- POST requests.post() 一致
- PUT requests.put() 一致
- PATCH requests.patch() 一致
- DELETE requests.delete() 一致
Requests 库的head()方法
>>> r = requests.head('http://httpbin.org/get')
>>> r.headers
{'Content‐Length': '238', 'Access‐Control‐Allow‐Origin': '*', 'Access‐
Control‐Allow‐Credentials': 'true', 'Content‐Type':
'application/json', 'Server': 'nginx', 'Connection': 'keep‐alive',
'Date': 'Sat, 18 Feb 2017 12:07:44 GMT'}
>>> r.text
''
Requests库的post()方法
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post('http://httpbin.org/post', data = payload)
>>> print(r.text)
{ ...
"form": {
"key2": "value2",
"key1": "value1"
},
}
以及>>> r = requests.post('http://httpbin.org/post', data = 'ABC')
>>> print(r.text)
{ ...
"data": "ABC"
"form": {},
}
Requests库的put()方法
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.put('http://httpbin.org/put', data = payload)
>>> print(r.text)
{ ...
"form": {
"key2": "value2",
"key1": "value1"
},
}