Python标准库中提供了:urllib、urllib2、httplib等模块以供Http请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。
Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作。
1、安装Requests库
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ requests
2、使用Requests库
import requests
3、发送请求与接收响应(基本GET请求)
response = requests.get(url)
3.1、传送 parmas参数
参数包含在url中
response = requests.get("http://httpbin.org/get?name=zhangsan&age=22")
print(response.text)
通过get方法传送参数
data = {
"name": "zhangsan",
"age": 30
}
response = requests.get("http://httpbin.org/get", params=data)
print(response.text)
3.2、模拟发送请求头(传送headers参数)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"
}
response = requests.get("http://httpbin.org/get", headers=headers)
print(response.text)
4、发送请求与接收响应(基本POST请求)
response = requests.post(url, data = data, headers=headers)
5、response属性
属性 | 描述 |
---|---|
response.text | 获取str类型(Unicode编码)的响应 |
response.content | 获取bytes类型的响应 |
response.status_code | 获取响应状态码 |
response.headers | 获取响应头 |
response.request | 获取响应对应的请求 |
6、代理
proxies = {
"http": "https://175.44.148.176:9000",
"https": "https://183.129.207.86:14002"
}
response = requests.get("https://www.baidu.com/", proxies=proxies)