1.Requests库入门
中文文档:https://requests.readthedocs.io/zh_CN/latest/
gittub地址:https://github.com/requests/requests
更多信息在 http://www.python-requests.org
Requests库的7个主要方法
方法 | 说明 |
---|---|
requests.requests(method,url,**kwargs) | 构造一个请求,支撑一下各方法的基础方法 |
requests.get(url,params=None,**kwargs) | 获取一个HTML页面的信息;对应于HTTP的GET; |
requests.head(url,**kwargs) | 获取HTML网页的头部信息;对应于HTTP的HEAD |
requests.put(url,data=None,**kwargs) | 向HTML网页提交PUT(全局修改)请求;对应于HTTP的PUT;(根据提交内容的不同,自动存储信息为form形式或者data形式) |
requests.patch(url,data=None,**kwargs) | 向HTML网页提交局部修改请求;对应于HTTP的PATCH; |
requests.delete(url,**kwargs) | 向HTML网页提交删除请求;对应于HTTP的DELETE; |
import requests
r=requests.get("http://www.baidu.com")
print(r.status_code)
r.encoding='utf-8'
print(r.text)
1.1get()方法
最简单的代码就是
r=requests.get(url)
完整代码就是
requests.get(url,params=None,**kwargs)
-
URL:全称为Uniform Resource Locator统一资源定位符,包含了协议,服务器名称,路径和文件名等信息。
-
API:全称为application programming interface;应用程序编程接口;
-
params:字典或字符串格式作为参数增加到url中,是额外参数。
-
**kwargs:代表十二个控制访问的参数;
(1)data:字典,字符串或文件对象,作为Request对象的内容;
(2)json: JSON格式的数据作为Request对象的内容;
(3)headers:字典,HTTP头部信息;目的是将请求伪装成诸如浏览器,使用post方法向服务器发起访问;
(4)cookies:字典或者CookieJar,Request中的cookie;
(5) auth:元组,支持HTTP认证功能;
(6)files: 字典类型,向服务器传输文件;
(7)timeout: 设定超时时间,单位秒;
(8)proxies:字典类型,设定访问代理服务器,可以增加登录认证;
(9) allow_redirects:True/False,默认为True,重定向开关; //高级功能使用
(10)stream: 布尔值,默认为真,获取内容立即下载开关;//高级功能使用
(11)verify:布尔值,默认为真,认证SSL证书开关; //高级功能使用
(12)cert:保存本地SSL证书路径; //高级功能使用
13个参数通过赋值的方法来调用
使用get函数会内部生成一个Request对象,以及一个Response对象(也就是 r );
Response对象包含了Request对象发送的全部信息以及爬虫返回的全部内容
1.1.2对于Response对象
import requests
r=requests.get("http://www.baidu.com")
print(r.status_code)
r.encoding='utf-8'
print(r.text)
#返回r的类
print(type(r))
# <class 'requests.models.Response'>
#返回的头部信息
print(r.headers)
# {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Tue, 04 Feb 2020 17:24:26 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:24 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
1.1.2Response对象的属性
属性 | 说明 |
---|---|
r.status_code | HTTP请求返回的状态,200表示成功,404和其他表示失败; |
r.text | 响应内容的字符串形式;即url对应的页面内容 |
r.encoding | 从响应内容的头部信息猜测响应内容的编码方式 |
r.apparent_encoding | 从响应内容的内容信息分析响应内容的编码方式;(备选编码方式) |
r.content | 将爬取到的响应内容的二进制形式还原成响应内容; |
Response对象提供了一个单独的方法raise_for_status()方法
r.raise_for_status() | HTTP的请求返回状态不是200则产生 request.HTTPError; |
---|
- 基本流程
apparent_encoding是实实在在根据文本内容得出编码,比encoding更加准确,得到的文本内容更会是所需要的
import requests
r=requests.get("http://www.baidu.com")
print(r.status_code)
#200
print(r.text)
# <!DOCTYPE html>
# <!--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>ç™¾åº¦ä¸€ä¸‹ï¼Œä½ å°±çŸ¥é“</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 name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ–°é—»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è´´å§</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产å“</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å
³äºŽç™¾åº¦</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度å‰å¿
读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>æ„è§å馈</a> 京ICPè¯030173å· <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
print(r.encoding)# ISO-8859-1
print(r.apparent_encoding)#utf-8
r.encoding='utf-8'
print(r.text)#出现中文字符
# <!DOCTYPE html>
# <!--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>百度一下,你就知道</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 name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
#
# <class 'requests.models.Response'>
# {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Wed, 05 Feb 2020 15:34:33 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:24 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
1.2爬取网页的通用代码框架
网络连接有风险,顾异常处理很重要
1.2.1 Requests库的常见异常
异常 | 说明 |
---|---|
requests.ConnectionError | 网络连接错误异常,如DNS查询失败,拒绝连接等; |
requests.HTTPError | HTTP错误异常 |
requests.URLRequired | URL缺失异常 |
requests.TooManyRedirects | 超过最大重定向次数,产生重定向异常;对复杂连接访问常常出现的错误 |
requests.ConnectTimeout | 连接远程服务器超时异常; |
requests.Timeout | 请求URL超时,产生超时异常; |
requests.Timeout指整个过程超时,而requests.ConnectTimeout仅仅指链接远程服务器超时异常
import requests
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()#判断请求状态
r.encoding=r.apparent_encoding#更改编码形式
return r.text
except:
return "WRONG!"
if __name__=="__main__":
url="http://www.baidu.com"
print(getHTMLText(url))
1.3HTTP协议及Requests库方法
HTTP协议:Hypertext Transfer Protocol 超文本传输协议;是一个基于“请求与响应”模式的,无状态的(非时序)应用层协议;即用户发起请求,服务器发出相应响应,无状态表示第一次访问与第二次访问无实质性联系
HTTP协议采用URL作为定位网络资源的标识
URL就是通过HTTP协议存取资源的internet路径,一个URL对应一个数据资源
PATCH的最主要好处就是节省 网络带宽
1.1.4Requests库主要方法解析
params:字典或字符串格式作为参数增加到url中,是额外参数。
import requests
#params
kv={'key':'value1','key2':'value2'}
r=requests.request('GET','http://python123.io/ws',params=kv)
print(r.url)
#https://python123.io/ws?key=value1&key2=value2
**kwargs:代表十二个控制访问的参数;
(1)data:字典,字符串或文件对象,作为Request对象的内容;
(2)json: JSON格式的数据作为Request对象的内容;
(3)headers:字典,HTTP头部信息;目的是将请求伪装成诸如浏览器,使用post方法向服务器发起访问;
(4)cookies:字典或者CookieJar,Request中的cookie;
(5) auth:元组,支持HTTP认证功能;
(6)files: 字典类型,向服务器传输文件;
(7)timeout: 设定超时时间,单位秒;
(8)proxies:字典类型,设定访问代理服务器,可以增加登录认证;
(9) allow_redirects:True/False,默认为True,重定向开关; //高级功能使用
(10)stream: 布尔值,默认为真,获取内容立即下载开关;//高级功能使用
(11)verify:布尔值,默认为真,认证SSL证书开关; //高级功能使用
(12)cert:保存本地SSL证书路径; //高级功能使用
import requests
#params
kv={'key':'value1','key2':'value2'}
r=requests.request('GET','http://python123.io/ws',params=kv)
print(r.url)
#https://python123.io/ws?key=value1&key2=value2
#headers:字典,HTTP定制头
hd={'user-agent':'Chrome/10'}#Chrome浏览器的第十个版本
r=requests.request('POST','http://python123.io/ws',headers=hd)
#fs
fs={'file':open('data.xls','rb')}
r=requests.request('POST','http://python123.io/ws',file=fs)
#proxies
pxs={'http':'http://user:[email protected]:1234'
'https''https://10.10.10.1:4321'}
r=requests.request('GET','http:www.baidu.com',proxies=pxs)
#访问地址时就是使用代理服务器的地址,有效的防止反追踪