活动地址:CSDN21天学习挑战赛

1.requests模块概述

本文主要介绍requests的http模块,该模块主要用于发送请求获取响应,该模块有很多的替代模块,比如urlib模块,但是工作中用的最多的还是requests模块,requests模块的代码简洁、易懂,相对于臃肿的urlib模块,使用requests编写的爬虫代码数量会更少,而且实现某一功能会简单。

2.requests常用属性或方法

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&amp;tpl=mn&amp;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>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使ç¨ç¾åº¦åå¿è¯»</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>æè§åé¦</a>&nbsp;京ICPè¯030173å·&nbsp; <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&amp;tpl=mn&amp;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>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <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&amp;tpl=mn&amp;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>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <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:#发送请求获取响应,超时设置为10sresponse = 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) #输出:整个网页源码

21天学习挑战赛——Python爬虫 requests库相关推荐

  1. 21天学习挑战赛——Python爬虫 lxml库与Xpath提取网页数据

    目录 ​1. 爬虫提取网页数据流程图 2. lxml库 2.1 解析HTML网页 3. Xpath 3.1 选取节点 3.2 谓语 3.3 选取未知节点 3.4 选取若干元素 4. Xpath实战 4 ...

  2. 已解决(Python爬虫requests库报错 请求异常SSL错误,证书认证失败问题)requests.exceptions.SSLError: HTTPSConnectionPool

    成功解决(Python爬虫requests库报错 请求异常,SSL错误,证书认证失败问题)requests.exceptions.SSLError: HTTPSConnectionPool(host= ...

  3. CSDN21天学习挑战赛——Python常用标准库概述

    ​活动地址:CSDN21天学习挑战赛 Python有一套标准库,随着python一起安装在电脑中,是python的一个组成部分. 一.os操作系统库 os模块提供了很多与操作系统相关联的函数. 在导入 ...

  4. 【python】python爬虫requests库详解

    1.安装:pip install requests 简介:Requests是一个优雅而简单的Python HTTP库,与之前的urllibPython的标准库相比,Requests的使用方式非常的简单 ...

  5. Python爬虫——Requests 库基本使用

    文章目录 Python爬虫--Requests 库基本使用 1.Requests简介和下载 2.Requests 库基本使用 Python爬虫--Requests 库基本使用 1.Requests简介 ...

  6. python爬虫requests库_python爬虫基础教程:requests库(二)代码实例

    get请求 简单使用 import requests ''' 想要学习Python?Python学习交流群:973783996满足你的需求,资料都已经上传群文件,可以自行下载! ''' respons ...

  7. 【Python成长之路】Python爬虫 --requests库爬取网站乱码(\xe4\xb8\xb0\xe5\xaf\x8c\xe7\x9)的解决方法

    [写在前面] 在用requests库对自己的CSDN个人博客(https://blog.csdn.net/yuzipeng)进行爬取时,发现乱码报错(\xe4\xb8\xb0\xe5\xaf\x8c\ ...

  8. python爬虫requests库_Python爬虫(三)Requests库

    什么是Requests Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库.与urllib相比,Requests更加方便,可以节约 ...

  9. 【Python成长之路】Python爬虫 --requests库爬取网站乱码(\xe4\xb8\xb0\xe5\xa)的解决方法【华为云分享】

    [写在前面] 在用requests库对自己的CSDN个人博客(https://blog.csdn.net/yuzipeng)进行爬取时,发现乱码报错(\xe4\xb8\xb0\xe5\xaf\x8c\ ...

最新文章

  1. vim block vim_如何不再害怕Vim
  2. 深度学习时代,调包侠没有未来,但是这个“包”有
  3. c语言 判断一个图是否全连通_C语言:程序运行流程图与顺序结构语句
  4. 【51单片机快速入门指南】7:片上EEPROM
  5. 工作399-openType=“getUserInfo“ lang=“zh_CN“ bindgetuserinfo=“getUserInfo“
  6. sql server 2005 COUNT_BIG (Transact-SQL)
  7. 查找两个单词链表共同后缀的起始结点(C++,单链表/双向链表解法)
  8. Spring Boot 针对 Java 开发人员的安装指南
  9. DotNetBar 教程
  10. java webservice用户验证_java webservice 用户验证 (服务端 + 客户端)
  11. Oracle DBA手记3:数据库性能优化与内部原理解析
  12. 1.编写一个程序,它从标准输入读取C源代码,并验证所有的花括号都正确的成对出现。
  13. 江苏省计算机等级考试注意事项,江苏省淮安市2020上半年计算机等级考试注意事项...
  14. FMEA软件版本及差异管理(FMEAHunter)
  15. NVIDIA Riva中文手册 (五) —— Riva TTS语音合成API的使用
  16. Mac —— QuickTime录屏 声音小解决
  17. 手把手教你如何将chatgpt接入微信公众号
  18. Given a binary search tree with its preorder traversal sequence { 8, 2, 15, 10, 12, 21 }.…
  19. CAD删除数据库对象
  20. perl mysql 数据推拉_科学网—从MySQL数据库中提取序列并进行引物设计的perl脚本 - 闫双勇的博文...

热门文章

  1. uniapp加载本地图片的坑
  2. 关于teamcity使用手册
  3. 关于理想的课堂作文——2009的美好愿景
  4. WIFI WPA/WPA2加密方式
  5. 入门学习爬取贴吧图片(附完整代码),2021/1/27有效
  6. Shiro 报UnavailableSecurityManagerException
  7. 如何将字节流转换成字符流
  8. 小程序的餐饮之路:从流量捕手到流量塘主的进阶秘籍
  9. 电赛汇总(二):常用传感器电路模块设计
  10. 潮州职业计算机学校,潮州职业技术学校2021年有哪些专业