requests库详解 --Python3
本文介绍了requests库的基本使用,希望对大家有所帮助。
requests库官方文档:https://2.python-requests.org/en/master/
一、请求:
1、GET请求
coding:utf8
import requests
response = requests.get('http://www.httpbin.org/get')
print(response.text)
2、POST请求
# coding:utf8
import requests
data = {
'name': 'Thanlon',
'age': 22,
'sex': '男'
}
response = requests.post('http://httpbin.org/post', data=data)
print(response.text)
3、解析json
# coding:utf8
import requests, json
response = requests.get('http://www.httpbin.org/get')
print(type(response.text))
# print(response.text)
print(response.json()) # 等价于json.loads(response.text)
print(type(response.json()))
4、获取二进制数据
# coding:utf8
import requests
response = requests.get('https://www.baidu.com/img/dong_5af13a1a6fd9fb2c587e68ca5038a3c8.gif')
print(type(response.text))
print(type(response.content))
print(response.text)
print(response.content) # 二进制流
5、保存二进制文件(图片、视频)
# coding:utf8
import requests
response = requests.get('https://www.baidu.com/img/dong_5af13a1a6fd9fb2c587e68ca5038a3c8.gif')
with open('image.gif', 'wb') as f:
f.write(response.content)
f.close()
6、添加headers(有需要添加请求头信息,否则请求不到,如“知乎”)
# coding:utf8
# get请求,添加headers
import requests
headers = {
'user-agent': 'Mouser-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36zilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
}
response = requests.get('https://www.zhihu.com/explore', headers=headers)
print(response.text)
#coding:utf8
#post请求,添加headers
import requests
data = {
'name': 'Thanlon',
'age': 22,
'sex': '男'
}
headers = {
'user-agent': 'Mouser-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36zilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
}
response = requests.post('http://httpbin.org/post', data=data, headers=headers)
print(response.text)
二、响应(response)
1、response相关属性
#coding:utf8
import requests
response = requests.get('http://httpbin.org')
print(type(response.status_code), response.status_code)#状态码 <class 'int'>
print(type(response.headers), response.headers)#响应头 <class 'requests.structures.CaseInsensitiveDict'>
print(type(response.cookies), response.cookies)#cookie <class 'requests.cookies.RequestsCookieJar'>
print(type(response.url), response.url)#请求的url <class 'str'>
print(type(response.history), response.history) # 访问的历史记录 <class 'list'>
2、状态码判断
#coding:utf8
import requests
response = requests.get('http://httpbin.org')
if not response.status_code == requests.codes.ok:#requests.codes.ok等价于200
pass
else:
print('Request Successfully')
3、文件上传
#coding:utf8
import requests
files = {
'file': open('image.gif', 'rb') # file可自定义
}
response = requests.post('http://httpbin.org/post', files=files)
print(response.text)
4、获取cookies
#coding:utf8
import requests
response = requests.get('http://www.baidu.com')
print(response.cookies)
print(response.cookies.items()) # [('BDORZ', '27315')]
for key, value in response.cookies.items():
print(key + '=' + value)

5、会话维持:模拟登录(相当于一个浏览器在请求)
#coding:utf8
import requests
s = requests.Session()
s.get('http://httpbin.org/cookies/set/BDORZ/123456')
response = s.get('http://httpbin.org/cookies')
print(response.text)
6、证书验证
#coding:utf8
import requests
response = requests.get('https://www.12306.cn')
print(response.status_code)
#coding:utf8
import requests, urllib3
urllib3.disable_warnings() # 消除警报信息
response = requests.get('https://www.12306.cn', verify=False) # verify默认是True
print(response.status_code) # 没有进行证书验证,有警报信息,
7、指定证书
#coding:utf8
import requests
response = requests.get('https://www.12306.cn', cert={'/path/server.crt', '/path/key'})
print(response.status_code)
8、代理的设置
#coding:utf8
import requests
proxies = {
'http': 'http://127.0.0.1:9743',
'https': 'https://127.0.0.1:9743'
}
response = requests.get('https://www.taobao.com', proxies=proxies)
print(response.status_code)
9、代理的设置(存在用户名和密码的情况下)
#coding:utf8
import requests
proxies = {
'http': 'http://user:password@127.0.0.1:9743',
'https': 'https://user:password@127.0.0.1:9743'
}
response = requests.get('https://www.taobao.com', proxies=proxies)
print(response.status_code)
10、socks代理
import requests
proxies = {
'http': 'socks5://127.0.0.1:9743',
'https': 'socks5://127.0.0.1:9743'
}
response = requests.get('https://www.taobao.com', proxies=proxies)
print(response.status_code)
11、超时设置
#coding:utf8
import requests
response = requests.get('http://httpbin.org', timeout=1)
print(response.status_code)
12、认证设置
遇到401错误,即:请求被禁止,需要加上auth参数
#coding:utf8
import requests
from requests.auth import HTTPBasicAuth
response = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
#response = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print(response.status_code)
13、异常处理
#coding:utf8
import requests
from requests.exceptions import ReadTimeout, HTTPError, RequestException, ConnectionError
try:
response = requests.get('http://httpbin.org', timeout=0.3)
print(response.status_code)
except ReadTimeout:
print('Timeout')
except HTTPError:
print('Http Error')
# except ConnectionError:
# print('Connection Error')
except RequestException:
print('Request Error ')
requests库详解 --Python3的更多相关文章
- python WEB接口自动化测试之requests库详解
由于web接口自动化测试需要用到python的第三方库--requests库,运用requests库可以模拟发送http请求,再结合unittest测试框架,就能完成web接口自动化测试. 所以笔者今 ...
- Python爬虫:requests 库详解,cookie操作与实战
原文 第三方库 requests是基于urllib编写的.比urllib库强大,非常适合爬虫的编写. 安装: pip install requests 简单的爬百度首页的例子: response.te ...
- python接口自动化测试之requests库详解
前言 说到python发送HTTP请求进行接口自动化测试,脑子里第一个闪过的可能就是requests库了,当然python有很多模块可以发送HTTP请求,包括原生的模块http.client,urll ...
- 爬虫学习--Requests库详解 Day2
什么是Requests Requests是用python语言编写,基于urllib,采用Apache2 licensed开源协议的HTTP库,它比urllib更加方便,可以节约我们大量的工作,完全满足 ...
- Python爬虫学习==>第八章:Requests库详解
学习目的: request库比urllib库使用更加简洁,且更方便. 正式步骤 Step1:什么是requests requests是用Python语言编写,基于urllib,采用Apache2 Li ...
- urllib库详解 --Python3
相关:urllib是python内置的http请求库,本文介绍urllib三个模块:请求模块urllib.request.异常处理模块urllib.error.url解析模块urllib.parse. ...
- Python爬虫系列-Requests库详解
Requests基于urllib,比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求. 实例引入 import requests response = requests.get( ...
- python的requests库详解
快速上手 迫不及待了吗?本页内容为如何入门 Requests 提供了很好的指引.其假设你已经安装了 Requests.如果还没有,去安装一节看看吧. 首先,确认一下: Requests 已安装 Req ...
- requests库详解
import requests #实例引入 # response = requests.get('http://www.baidu.com') # print(type(response)) # pr ...
随机推荐
- mongo中常用的增删改查
db.students.find();//按性别分组,并显示每组的姓名db.students.aggregate({ $group:{ _id:'$sex', name:{$push:'$name'} ...
- day1:java学习第一天之eclipse安装
选择开发语言的学习其实不用纠结,如果你说自己是做开发的,连最流行的开发语言都不会,好像说不过去,并且最流行也说明用的人多,优秀的人也会,自己要提高要多向优秀的人学习.想明白这点其实选择就好说了,再一个 ...
- gvim keil 快捷跳转至出现错误(警告)行
开发环境 win7系统中:用keil 对工程进行编译链接,用gvim编辑查看源文件. 实现效果 一键跳转到出现警告或者错误的源码. 实现原理 gvim 调用外部shell脚本,对keil编译生成的lo ...
- ajax 防止重复提交
参考链接:http://www.hollischuang.com/archives/931 http://blog.csdn.net/everything1209/article/details/52 ...
- python -yield理解
参考:https://foofish.net/iterators-vs-generators.html 从网上看到一个面试题,求最后的输出结果: def add(n, i): return n+ide ...
- svn与cvs的一些比较
所有的文档都显示SVN可以取代CVS,同时SVN的问题和缺点都被隐藏了.不幸的是,我们并不认为SVN是CVS的替代品,尽管很多缺陷都被修改了.更有甚者,它甚至让人重回VSS.CVS和SVN的比较类似与 ...
- GoldenGate HANDLECOLLISIONS参数使用说明
HANDLECOLLISIONS在官方文档上的说明: 使用HANDLECOLLISIONS和NOHANDLECOLLISIONS参数来控制在目标上应用SQL时,Replicat是否尝试解决重复记录和缺 ...
- npm命令
简介:npm(node.js package manager)是Node.js的包管理器 .它创建于2009年,作为一个 开源项目,帮助开发人员轻松共享打包的代码模块 ## 默认方式初始化npm.(进 ...
- Java集合中的细节
integer数据对比 对于Integer var = ? 在-128至127范围内的赋值,Integer对象是在IntegerCache.cache产生,会复用已有对象,这个区间内的Integer值 ...
- js之数组操作
js之数组操作 前言 本文主要从应用来讲数组api的一些操作,如一行代码扁平化n维数组.数组去重.求数组最大值.数组求和.排序.对象和数组的转化等.(文章摘自:https://segmentfault ...