python 基础10 requests

requests 官方文档:
https://requests.readthedocs.io/projects/cn/zh-cn/latest/
快速上手
https://requests.readthedocs.io/projects/cn/zh-cn/latest/user/quickstart.html
安装 找到目标路径 Scripts
pip install requests -i https://pipy.douban.com/simple

发送请求简洁:

import requests

r = requests.get('https://github.com/Ranxf')       # 最基本的不带参数的get请求
r1 = requests.get(url='http://dict.baidu.com/s', params={'wd': 'python'})      # 带参数的get请求

我们就可以使用该方式使用以下各种方法:

1   requests.get(‘https://github.com/timeline.json’)                                # GET请求
2   requests.post(“http://httpbin.org/post”)                                        # POST请求
3   requests.put(“http://httpbin.org/put”)                                          # PUT请求
4   requests.delete(“http://httpbin.org/delete”)                                    # DELETE请求
5   requests.head(“http://httpbin.org/get”)                                         # HEAD请求
6   requests.options(“http://httpbin.org/get” )                                     # OPTIONS请求

为url传递参数:

url_params = {'key':'value'}       #    字典传递参数,如果值为None的键不会被添加到url中
r = requests.get('your url',params = url_params)
print(r.url)
your url?key=value

响应的内容:

r.encoding                       #获取当前的编码
r.encoding = 'utf-8'             #设置编码
r.text                           #以encoding解析返回内容。字符串方式的响应体,会自动根据响应头部的字符编码进行解码。
r.content                        #以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。
r.headers                        #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
r.status_code                     #响应状态码
r.raw                             #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read()   
r.ok                              # 查看r.ok的布尔值便可以知道是否登陆成功
 #*特殊方法*#
r.json()                         #Requests中内置的JSON解码器,以json形式返回,前提返回的内容确保是json格式的,不然解析出错会抛异常
r.raise_for_status()             #失败请求(非200响应)抛出异常
r.url    返回地址

https://www.cnblogs.com/simono/p/16629306.html
https://blog.csdn.net/qq_69183322/article/details/136099661
https://blog.csdn.net/qq_37616069/article/details/80376776
https://blog.csdn.net/Myon5/article/details/135817182

posted @ 2024-07-14 18:59  donghongchao  阅读(4)  评论(0编辑  收藏  举报