requests库详解

1、requests库简介:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html(官网)

What is requests?

答:基于urllib库的简单易用的http库

2、安装

pip3 install requests

3、用法详解

(1)、实例(小伙伴们来感受下其的魅力吧!)

(2)、发送请求

主要包含以下方式:

import requests

requests.get('http://www.ujs.edu.cn/')

requests.post('http://www.ujs.edu.cn/post')

requests.put('http://www.ujs.edu.cn/put')

requests.delete('http://www.ujs.edu.cn/delete')

requests.head('http://www.ujs.edu.cn/get')

requests.options('http://www.ujs.edu.cn/get')

小伙伴们主要掌握前两种其他了解即可

1、get请求使用

解析json

获取二进制数据

下面小伙们我们来做个实验:(随便下载网上一张图片到本地)

方法:随便打开一张图片并右键得到其链接

运行效果图

添加headers

这样我们搞到了知乎的源码

2、post请求使用

响应

常用属性总结:

response.status_code-获取响应的状态吗 200 表示成功/ http://tool.oschina.net/commons?type=5(状态码含义详解网站)

response.text-获取文本内容

resposne.headers-获取请求头信息

response.cookies-获取cookies信息(cookies我的理解是相当于访问网页时的个人身份证)

response.content-获取响应的二进制内容,下载图片和视频时使用

response.url-获取响应的url

response.history-获取响应的历史信息

3、高级操作

文件上传

获取cookie

会话维持(模拟登陆,小伙伴们咱们下面来探讨!)

获取结果为:cookies ={}

结果为:cookies ={'number':'12345678'}

证书认证

代理设置(官方文档:http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced)

 

这里我使用了在讯代理上购买的一个代理而且该该代理需要账号密码才能使用,我们使用它访问了淘宝并获取了源码

此外新版的requests库还支持SOCKS代理

用法如下:

首先安装依赖库:pip install requests[socks]

proxies = {

  'http': 'socks5://user:pass@host:port',

  'https': 'socks5://user:pass@host:port'

}

其用法与http和https代理完全一样,这里不再重述,小伙伴们可以自己试下

超时设置(限制服务器应答速度)

小伙伴们咱们再来请求下国外的网站

异常捕获(咱们来捕获这个connectimeout异常这样程序就不会在运行中中断了!)

认证设置

异常处理:http://www.python-requests.org/en/master/api/#exceptions(官网)

原文地址:https://www.cnblogs.com/518894-lu/p/9013022.html