活动地址:CSDN21天学习挑战赛
1.requests模块概述
本文主要介绍requests的http模块,该模块主要用于发送请求获取响应,该模块有很多的替代模块,比如urlib模块,但是工作中用的最多的还是requests模块,requests模块的代码简洁、易懂,相对于臃肿的urlib模块,使用requests编写的爬虫代码数量会更少,而且实现某一功能会简单。
2.requests常用属性或方法
方法/属性 | 说明 |
---|---|
response = requests.get(url) | 发送请求获取的响应对象(最常用) |
response = requests.post(url) | 发送请求获取的响应对象 |
response.url | 响应的url,有时候响应的url和请求的url不一致 |
response.satus_code | 响应状态码,如:200、404 |
response.request.headers | 响应对应的请求头 |
response.headers | 响应头 |
response.request.cookies | 响应对应请求的的cookie,返回cookieJar类型 |
response.cookies | 响应的cookie(警告了set-cookie动作,返回cookieJar类型) |
response.json() | 自动将json字符串类型的响应内容转换为Python对象(dic或list) |
response.text() | 返回响应的内容,str类型 |
response.content | 返回响应的内容,bytes类型 |
2.1 应用举例
import requests
#目标网址
url = 'https://www.baidu.com/'
#发送请求获取响应
reponse = requests.get(url) #输出:<class 'requests.models.Response'>
#查看响应对象的类型
print(type(reponse)) #输出:200
#查看响应状态码
print(reponse.status_code) #输出:<class 'str'>
#查看相应的内容的类型
print(type(reponse.text)) #输出:<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
#查看cookies
print(reponse.cookies) #输出:<!DOCTYPE html>
#查看响应的内容
print(reponse.text)
#输出:<!--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=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/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=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç¾åº¦ä¸ä¸ class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ°é»</a> <a href=https://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>
2.2 response.text和response.content的区别
response.text :
- 类型:str
- 解码类型:requests模块自动根据http头部对响应的编码作出有根据的推测,推测的文本编码
response.content :
- 类型:bytes
- 解码类型:没有指定,执行挑选
通过对response.content进行decode,来解决中文源码:
- response.content.decode() :默认utf-8
- response.content.decode('GBK')
常见的编码字符如下:
- uft-8
- gbk
- gb2312
- asci(读音:阿斯克码)
- iso-8859-1
应用举例:
import requests
#目标网址
url = 'https://www.baidu.com/'
#发送请求获取响应
reponse = requests.get(url) #输出:<class 'requests.models.Response'>
#手动设置编码格式
reponse.encoding = 'utf-8'
#打印源代码的str类型
print(reponse.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=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/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=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://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>
#response.content是存储的bytes类型的响应数据,进行decode操作
print(reponse.content.decode('utf-8'))
#输出:
# <!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=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/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=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://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>
2.3 发送带Headers参数请求
函数格式:requests.get(url, headers=headers)
参数说明:
- url为请求网址
- headers参数接收字典形式的请求头,请求头字段名为key,字段对应的值为value
获取请求头:
用法举例:
import requests
#目标网址
url = 'https://blog.csdn.net/m0_52162042?spm=1000.2115.3001.5343'
#构建请求头,最重要的是user-Agent
#如果需要其他请求,就在headers字典中加上
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
#发送请求获取响应
response = requests.get(url,headers=headers)
print(response.text)
#输出:整个网页源码
2.3.1 headers参数中携带cookies
网站经常利用请求头中的cookies字段来做用户访问状态的保持,那么我们可以在headers参数中添加cookies,模拟普通用户的请求。cookies具有时效性,过一段时间需要更换,而且里面包含了个人信息,切勿外传。
在headers字典中添加Cookie参数:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'Cookie': 'SUID=B16809706B20A00A000000005FAA56A2; SUV=007F3EDD700968B15FAA56A244092528; _y_1001=%E8%B4%AD%E7%89%A9%E5%BC%82%E5%BD%A2sogo_1110_2; _AD_1001=361604998826800; ssuid=9596610466; _m_1265=5235865654890; _AD_1265=5235865654893; ad_recall=%7B%2241861%22%3A1636013904683%7D; IPLOC=CN3715; Hm_lvt_13bcdac6f533873f736729fd894098ad=1660281832; Hm_lvt_eaa57ca47dacb4ad4f5a257001a3457c=1660281836; __mtmc=201094952; LSTMV=352%2C320; LCLKINT=2029; cd=1660375612&15b92f317554f79f73dcf21c955e624a; ld=NZllllllll2AdWyBYsNv5paTU0IAdCwDtjbw6lllllGllllxRylll5@@@@@@@@@@; Hm_lvt_d7c7037093938390bc160fc28becc542=1660441495; Hm_lpvt_d7c7037093938390bc160fc28becc542=1660441495; SNUID=217A94C1B2B457F72C68FB29B2ED69EB; GOTO=Af21997; __mtma=201094952.995483057.1604998820.1660561575.1660564900.82; __mtmz=201094952.1660564900.82.79.mtmcsr=801100.anaih.com|mtmccn=(referral)|mtmcmd=referral|mtmcct=/; sduv=1660281830585_4535_00007; CKOR=2664_00007_00001; CKOD=2124_00002_00000; __mtmb=201094952.2.100.1660564900'
}
2.4 超时参数timeout
在平时上网时,我们经常会遇到网络波动,这时候,一个请求等了很久可能仍然没有响应。在爬虫中,一个请求很久没有结果,就会让整个项目效率变得非常低,所以这个时候我们就需要对请求进行强制性要求,让它在特定的时间内返回结果,否则就会报错。
函数语法:response = requests.get(url, timeout=3)
参数说明:
timeout=3 表示:发送请求后,3秒内返回响应,否则久抛出异常
用法举例:
import requests
#目标网址
url = 'https://blog.csdn.net/m0_52162042?spm=1000.2115.3001.5343'
#构建请求头,最重要的是user-Agent
#如果需要其他请求,就在headers字典中加上
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'
}
try:
#发送请求获取响应,超时设置为10s
response = requests.get(url,headers=headers,timeout=10)
except:
for i in range(4): #循环请求网站
response = requests.get(url,headers=headers,timeout=20)
if response.status_code==200:
break
html_str = response.text
2.5 proxies代理参数
为了让服务器以为不是同一个客户端在请求,防止频繁向同一个域名发送请求被封ip,所以我们需要使用代理ip。
函数语法:response = requests.get(url, proxies=proxies)
参数说明:
proxies的形式为字典
举例说明:
proxies = {
'http':'http://12.34.5678:9527',
'https':'https://12.34.5678:9527',
}
注意:如果proxies字典中包含有多个键值对时,发送请求时将按照url地址的协议来选择相应的代理ip。
2.6 发送post请求
requests模块发送post请求函数的其他参数和get请求的参数完全一致。
语法格式:response = requests.post(url, data)
应用举例:
以百度翻译为例,找到对应的请求,点击Payload,展开Form Data表单。
import requests
#目标网址
url = 'https://fanyi.baidu.com/#en/zh/love'
data = {
'query': 'love'
}
response = requests.post(url,data=data)
print(response.text) #输出:整个网页源码