目前较新的为 Python3 版本,推荐使用。Requests 是 Python 的一个好用的 HTTP 库,聪明的程序员的首选!
功能特性
Requests 允许你发送纯粹的 HTTP/1.1 请求,无需额外的操作,无需对 POST 提交的数据进行编码。另外,Keep-alive 和 HTTP 连接池都是 100% 自动进行的。
Requests 完全满足当今 web 的需求:
- Keep-Alive & 连接池
- 国际化域名和 URLs
- 带 Cookie 的持久会话
- 浏览器式的 SSL 认证
- 内容自动解码
- 基本/摘要式身份认证
- 优雅的键/值 Cookie
- 自动解压
- Unicode 响应体
- 支持 HTTP(S) 代理
- 文件分块上传
- 流下载
- 连接超时
- 分块请求
- 支持 .netrc
安装
(1)打开dos命令运行窗口
(2)输入pip install Requests
使用
(1)导入
import Requests
(2)用法
请求方式:
import requests
requests.post("http://httpbin.org/post")
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get")
(3)实例
get 请求
无参数:
import requests
url = 'https://www.baidu.com/'
response = requests.get(url)
print(response.text)
有参数:
import requests
url = 'http://httpbin.org/get'
data = {
'name':'zhangsan',
'age':'25'
}
response = requests.get(url,params=data)
print(response.url)
print(response.text)
获取二进制数据
必须添加header
import requests
url = 'https://www.zhihu.com/'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
}
response = requests.get(url,headers=headers)
print(response.text)
POST请求
通过post把数据提交到url地址,等同于一字典的形式提交form表单里面的数据
import requests
url = 'http://httpbin.org/post'
data = {
'name':'jack',
'age':'23'
}
response = requests.post(url,data=data)
print(response.text)
结果:
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "23",
"name": "jack"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "16",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.13.0"
},
"json": null,
"origin": "118.144.137.95",
"url": "http://httpbin.org/post"
}
文件上传
import requests
url = "http://httpbin.org/post"
files= {"files":open("test.jpg","rb")}
response = requests.post(url,files=files)
print(response.text)
获取cookie
import requests
response = requests.get('https://www.baidu.com')
print(response.cookies)
for key,value in response.cookies.items():
print(key,'==',value)
会话维持
cookie的一个作用就是可以用于模拟登陆,做会话维持
import requests
session = requests.session()
session.get('http://httpbin.org/cookies/set/number/12456')
response = session.get('http://httpbin.org/cookies')
print(response.text)