园岭网站建设,建筑工程网课视频,辽宁省交通建设投资集团网站,济南pc网站建设公司Requests: 让 HTTP 服务人类
虽然Python的标准库中 urllib 模块已经包含了平常我们使用的大多数功能#xff0c;但是它的 API 使用起来让人感觉不太好#xff0c;而 Requests 自称 “HTTP for Humans”#xff0c;说明使用更简洁方便。 Requests 唯一的一个非转基因的 Pyth…Requests: 让 HTTP 服务人类
虽然Python的标准库中 urllib 模块已经包含了平常我们使用的大多数功能但是它的 API 使用起来让人感觉不太好而 Requests 自称 “HTTP for Humans”说明使用更简洁方便。 Requests 唯一的一个非转基因的 Python HTTP 库人类可以安全享用 Requests 继承了urllib的所有特性。Requests支持HTTP连接保持和连接池支持使用cookie保持会话支持文件上传支持自动确定响应内容的编码支持国际化的 URL 和 POST 数据自动编码。
requests 的底层实现其实就是 urllib
Requests的文档非常完备中文文档也相当不错。Requests能完全满足当前网络的需求支持Python 2.6–3.5而且能在PyPy下完美运行。
开源地址https://github.com/kennethreitz/requests
中文文档 API http://docs.python-requests.org/zh_CN/latest/index.html
为什么重点学习requests模块而不是urllib
requests的底层实现就是urllib
requests在python2和python3中通用方法完全一样
requests简单易用
requests能够自动帮助我们解压gzip压缩的等网页内容
安装方式
利用 pip 安装 或者利用 easy_install 都可以完成安装
$ pip install requests$ easy_install requestsrequests的作用
作用发送网络请求返回响应数据
官方文档https://requests.readthedocs.io/zh_CN/latest/index.html
基本GET请求headers参数 和 parmas参数
1. 最基本的GET请求可以直接用get方法
response requests.get(http://www.baidu.com/)# 也可以这么写
urlhttp://www.baidu.com/
response requests.get(url)2. 添加 headers 和 查询参数
如果想添加 headers可以传入headers参数来增加请求头中的headers信息。如果要将参数放在url中传递可以利用 params 参数。
import requestskw {wd:长城}headers {User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36}# params 接收一个字典或者字符串的查询参数字典类型自动转换为url编码不需要urlencode()
response requests.get(http://www.baidu.com/s?, params kw, headers headers)# 查看响应内容response.text 返回的是Unicode格式的数据
print (response.text)# 查看响应内容response.content返回的字节流数据
print (respones.content)# 查看完整url地址
print (response.url)# 查看响应头部字符编码
print (response.encoding)# 查看响应码
print (response.status_code)小例子
通过requests获取百度首页
#codingutf-8
import requests
response requests.get(https://www.baidu.com/)
print(response.request.headers)
print(response.content.decode())获取新浪首页
#codingutf-8
import requests
response requests.get(http://www.sina.com)
print(response.request.headers)
print(response.text)产生问题的原因分析
requests默认自带的Accept-Encoding导致或者新浪默认发送的就是压缩之后的网页但是为什么content.read()没有问题因为requests自带解压压缩网页的功能当收到一个响应时Requests 会猜测响应的编码方式用于在你调用response.text 方法时对响应进行解码。Requests 首先在 HTTP 头部检测是否存在指定的编码方式如果不存在则会使用 chardet.detect来尝试猜测编码方式存在误差更推荐使用response.content.deocde()