
2.4 requests库的安装及使用
2.4.1 requests库概述
requests库是Python中的一个HTTP网络请求库,用来简化网络请求。通过对requests库的引用,便能够使用其中的成员(方法和属性),如图2-8所示。

图2-8 Requests库成员
2.4.2 requests库的安装
安装request库的操作步骤如下。
1)在PyCharm中选择“File”→“Settings”菜单命令,如图2-9所示。

图2-9 选择“File”→“Settings”菜单命令
2)弹出“Settings”对话框,在左侧窗格中依次选择“Project:pycharmprojects”→“Project Interpreter”选项,然后单击右上角的“+”按钮,如图2-10所示。

图2-10 “Setting”对话框
3)弹出“Available Packages”对话框,在搜索文本框中输入“requests”,选择列表框中出现的“requests”,然后单击“Install Package”按钮,如图2-11所示。

图2-11 “Available Package”对话框
2.4.3 requests库的基本用法
1.requests库的常用方法
(1)request()
requests.request()用于生成一个请求。这是一个总方法,可以通过传入不同的参数实现不同的目的。
语法:requests.request(method,url,∗∗kwargs)
参数说明:
1)method表示请求方式参数,共7个,分别为GET、POST、HEAD、PUT、PATCH、DELETE。必填。
2)url表示拟获取页面的URL链接。必填。
3)∗∗kwargs表示可选的控制访问参数,共13个,分别如下。
● params:字典或字节序列,作为参数增加到url中。
● data:字典、字节序列或文件对象,作为Request的内容。
● json:JSON格式的数据,作为Request的内容。
● headers:设置头部,字典类型,如{'user-agent':'my-app/0.0.1'}(模拟浏览器进行访问)。
● cookies:设置cookie,字典类型,如{"key":"value"}。
● auth:元组格式的数据。
● files:字典类型,传输文件。
● timeout:设置超时时间,以秒(s)为单位。
● proxies:设置代理,字典类型,如{"http":"http://10.10.1.10:8080"}。
● allow_redirects:True或False,默认为True,重定向开关。
● stream:True或False,默认为True,获取内容立即下载开关。
● verify:True或False,默认为True,认证SSL证书开关。
● cert:本地SSL证书路径。
【例2-1】使用requests的request()方法以字典数据作为参数获取github的API数据。

(2)get()
requests.get()是指使用GET方法获取指定的URL。
语法:requests.get(url,params={},headers={},cookies={},allow redirects=True,timeout=float,proxies={},verify=True)
【例2-2】使用requests的get()方法以字典数据作为参数获取github的API数据。

(3)post()
requests.post()是指使用POST方法获取指定URL。以表单形式发送数据时,只需传递一个字典数据给data关键字,在发送请求的时候,会自动编码为表单的形式。
语法:requests.post(url,data={},headers={},cookies={},json=' ',files={},allow_redirects=True,timeout=float,proxies={},verify=True)
【例2-3】使用requests的post()方法以字典数据作为参数获取github的API数据。

(4)head()
requests.head()是指使用HEAD方法获取页面的头部信息。
【例2-4】使用requests的head()方法获取指定URL的头部信息。


2.requests库的对象属性
1)requests.status_code是指返回状态码。
2)requests.text是指返回的页面内容。
3)requests.encoding是指返回页面内容使用的可能的编码方式。如果网页没有设置charset的值,就使用默认的编码格式。
4)requests.apparent_encoding是指返回对页面内容分析后的编码方式。
5)requests.content是指以二进制的形式返回response的内容。
3.一个简单的requests库实现案例
使用requests库显示百度页面的各属性值。
1)在Python文件中导入requests库。

2)使用requests.get()方法获得指定URL。

3)查看返回的requests对象属性值。

4)显示结果如图2-12所示。

图2-12 百度页面的属性值