Requests库

Requests库是一个流行的用于发出HTTP请求的Python库。它将发出请求的复杂性抽象到一个简单的API后面,允许用户使用Python发送HTTP/1.1请求。

1. Requests的安装

在终端使用命令: 

pip install requests -i https://pypi.douban.com/simple/   #  Windows 

python3 -m pip install requests -i https://pypi.douban.com/simple/      # Mac

2. Requests常用的方法

发起get请求 --- requests.get()

发起post请求 --- requests.post()

发起put请求 --- requests.put()

发起delete请求 --- requests.delete()

当然,为了自动管理cookie,也可以使用session发起requests:

首先 创建session 对象 session = requests.session()

然后通过session发起requests: resp = session.request()

3. 对响应对象变量resp的一般处理

resp.status_code  --- 获取响应状态码

resp.text --- 获取响应内容,结果类型是字符串

resp.json() --- 获取响应内容,结果是字典类型

resp.headers --- 获取响应headers

4. Sample

import requests

url ='https://api.github.com/search/repositories?q=language:python&sort=stars'

resp = requests.get(url=url)

res_code = resp.status_code

res_text = resp.text

res_dict = resp.json()

print(res_code)

print(res_text)

print(res_dict)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容