Python Requests 使用举例
HDUZN

在Python中,Requests 是一个非常常用的第三方库,用于发送HTTP请求。它提供了简洁而直观的API,使得发送HTTP请求变得非常容易。requests库可以用于发送GET、POST、PUT、DELETE等各种类型的请求,并且支持处理Cookie、Session、文件上传等功能。

官方文档:https://requests.readthedocs.io/en/latest/

安装 requests 包

1
pip install requests

使用 requests 库

1.Get 请求

1
2
3
4
5
6
7
8
9
10
11
import requests # 导入requests库

def get_test():
ques = "今日天气" # 设置问题为"今日天气"
url = "http://127.0.0.1:8080/chat?q=" + ques # 构建请求的URL
response = requests.get(url) # 发送GET请求
result = response.json() # 将响应内容解析为JSON格式
# result = response.text
print(result) # 打印结果

get_test()

用法很简单,主要看请求返回的数据,如果是 json格式的,就用 result = response.json() 直接得到 json格式数据,再看具体需要哪一项。如果不是 json 格式,直接用 result = response.text 文本格式就行。

2.Post 请求

1
2
3
4
5
6
7
8
9
10
11
12
import requests

def post_test():
url = "http://127.0.0.1:8080/chat"
response = requests.post(url, data={'question': '今天天气'}) # 设置问题为"今日天气"

print(response.status_code) # 响应状态码
if (response.status_code == 200): # 状态码200时,表示正常
result = response.json()
print((result["answer"])) # 响应内容中对应 "answer"的值

post_test()

如果调用API接口,一般没啥问题,但如果是自己写的接口,可能就会碰到返回的结果有乱码的问题。

用Python的Web框架(Bottle或Flask)写接口的时候,就碰到了这个问题,解决方法:Python 写接口时编码问题

  • 本文标题:Python Requests 使用举例
  • 本文作者:HDUZN
  • 创建时间:2023-06-29 14:38:02
  • 本文链接:http://hduzn.cn/2023/06/29/Python-Requests使用举例/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论