Python-requests模块学习

Requests模块说明

Requests 是使用 Apache2 Licensed 许可证的 HTTP 库。用 Python 编写,真正的为人类着想。

Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

在Python的世界里,事情不应该这么麻烦。

Requests 使用的是 urllib3,因此继承了它的所有特性。Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。现代、国际化、人性化。

(以上转自Requests官方文档)

请求

requests主要的的方法有7个,分别对应HTTP协议的GET、HEAD、POST、PUT、PATCH、DELETE六个+request()方法,最常用的就是get和post请求。

构造一个向服务器请求资源的Requests对象,返回一个包含服务器资源的Response对象。

image-20210331210906326

request方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
request(method,url,**kwargs)

method:请求方法,对应get/put/post等7种
url:拟获取页面的url链接
**kwargs:13个控制访问参数
params:字典或字节序列,作为参数添加到url中
data:字典、字节序列或文件对象,作为Request的内容
json:JSON格式的数据,作为Request的内容
headers:字典,HTTP定制头
cookies:字典或CookieJar,Request中的cookie
auth:元组,支持HTTP认证功能
files:字典类型,传输文件
timeout:设定超时时间,秒为单位
proxies:字典类型,设定访问代理服务器,可以增加登入认证
allow_redirects:True/False,默认为True,重定向开关
stream:True/False,默认为True,获取内容立即下载
verify:True/False,默认为True,认证SSL证书开关
cert:本地SSL证书路径

GET方法

1
2
3
4
5
get(url,params = None,**kwargs)

url:拟获取页面的url连接
params:url中的额外参数,字典或字节流格式,可选
**kwargs:12个控制访问参数,继承自request

POST方法

1
2
3
4
5
6
post(url,data=None,json=None,**kwargs)

url:拟获取页面的url连接
data:字典、字节序列或文件对象,作为Request的内容
json:JSON格式的数据,作为Request的内容
**kwargs:12个控制访问参数,继承自request

Response对象属性

还有:

r.url:内容为请求的url

r.cookies:cookie信息

Requests库的异常

image-20210331220143952

还有:

r.raise_for_status():如果不是200,产生异常requests.HTTPError

请求实例

1基本的GET请求

1
2
3
4
5
import requests

# 使用 get 方式请求
response = requests.get('https://tieba.baidu.com/')
print(response.text)

2发送GET带参数,对变量params传入字典数据类型

1
2
3
4
5
6
7
8
import requests

url = 'http://httpbin.org/get'
payload = {'name': 'Numb', 'author': 'Linkin Park'}

response = requests.get(url, params=payload)
print(response.url)
print(response.text)

2.1params同时支持传入列表,达到一个变量赋两个值的效果

1
2
3
4
5
6
7
8
import requests
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

r = requests.get('http://httpbin.org/get', params=payload)

print(r.url)

#输出 : http://httpbin.org/get?key1=value1&key2=value2&key2=value3

3发送POST请求,使用data参数传输数据

3.1直接传输字典类型到data参数,作为POST请求的数据,会自动编码为表单形式发送,requests默认使用application/x-www-form-urlencoded对POST数据编码。如果要传递JSON数据,可以直接传入json参数

1
2
3
4
5
6
7
8
9
import requests

url = 'http://httpbin.org/post'
data = {
'user': 'abc123',
'pass': 'admin'
}
response = requests.post(url, data=data)
print(response.text)

上传文件需要更复杂的编码格式,但是requests把它简化成files参数:

1
2
upload_files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=upload_files)

3.2通过json参数传递json数据到服务器,Requests库会自动编码,这是新特性,如果还是依靠data参数传递json数据,则需要使用json模块进行数据编码再传递给data参数,复杂了一点,不推荐了吧

1
2
3
4
import requests
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)##传递json数据给json参数

4 Request库发送get或者post请求后会得到一个response对象,这个对象包含了很多有用的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import requests

url = "http://httpbin.org/post"

data = {'user':'abc123','passwd':'admin123'}

r = request.post(url,data=data)

print(r.url) # 返回请求的url
print(r.text) # 返回请求的文本字符串
print(r.content) # 返回响应内容的二进制形式
print(r.headers) # 返回请求头
print(r.cookies) # 返回cookies
print(r.status_code) # 返回请求的状态码
print(r.encoding) # 返回从HTTP header中猜测的响应内容编码方式
print(r.apparent_encoding) # 返回从内容中分析出的响应内容编码方法(备选编码方式)

5 Session机制:requests库如何保持session,详细参考下面的官方代码示例

1
2
3
4
5
6
7
8
9
s = requests.Session() # 生成一个session对象

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789') # 有示例网站取得sessioncookie

r = s.get("http://httpbin.org/cookies") # 再次发送请求到示例网站,示例网站会返回你的cookie

print(r.text) #由此回复证明第二次请求也带上了sessioncookie

# 输出:'{"cookies": {"sessioncookie": "123456789"}}'

不过需要注意,就算使用了会话,方法级别的参数也不会被跨请求保持。下面的例子只会和第一个请求发送 cookie ,而非第二个:

1
2
3
4
5
6
7
8
9
s = requests.Session()

r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'}) #使用了方法级别的参数cookies
print(r.text)
# '{"cookies": {"from-my": "browser"}}'

r = s.get('http://httpbin.org/cookies') #第二次请求cookies方法设置的请求消失了
print(r.text)
# '{"cookies": {}}'

在平时网上冲浪的过程中,我们经常会遇到网络波动,这个时候,一个请求等了很久可能任然没有结果。

在爬虫中,一个请求很久没有结果,就会让整个项目的效率变得非常低,这个时候我们就需要对请求进行强制要求,让他必须在特定的时间内返回结果,否则就报错。

超时参数timeout的使用方法

1
response = requests.get(url, timeout=3)  【默认是3s,这个时间有点长】

timeout=3表示:发送请求后,3秒钟内返回响应,否则就抛出异常

1
2
3
4
5
6

import requests


url = 'https://twitter.com'
response = requests.get(url, timeout=3) # 设置超时时间

结果会报错:

image-20210331221129704

设置访问代理:

1
2
3
4
5
proxies = {
"http": "http://10.10.10.10:8888",
"https": "http://10.10.10.100:4444",
}
r = requests.get('http://m.ctrip.com', proxies=proxies)

xml请求

1
2
3
4
5
6
7
headers = {'Content-type': 'text/xml'}
XML = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>'
url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx'
r = requests.post(url,headers=headers,data=XML)
#r.encoding = 'utf-8'
data = r.text
print data

参考文章

https://www.cnblogs.com/tangdongchu/p/4229049.html

https://blog.csdn.net/lady_killer9/article/details/109032337

https://juejin.cn/post/6844904008037957639

https://blog.csdn.net/qq_41151593/article/details/104578476

https://www.liaoxuefeng.com/wiki/1016959663602400/1183249464292448

https://blog.csdn.net/weixin_44799217/article/details/113062756

https://mp.weixin.qq.com/s?__biz=MzU5NjA0ODAyNg==&mid=2247484179&idx=3&sn=2a695394a24eabd1fc1a743312311375&chksm=fe69e2e6c91e6bf0a8ec25807a77bb3d25dfc117cb055957b3d108855944eca21b711dc22103&mpshare=1&scene=23&srcid=10319N8JtkTqaq3BUEGPvKhe&sharer_sharetime=1604394368415&sharer_shareid=a0847c60830277aa59000b154c48d9ab#rd

https://rick11929.github.io/2018/01/23/Python-requests%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/

中文文档:https://docs.python-requests.org/zh_CN/latest/index.html (翻译的有点烂,建议看英文原版)

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2020-2021 Blog of Tianze

请我喝杯咖啡吧~

支付宝
微信