python使用request发送请求并处理返回的结果

工作中不经常用到这个,但是偶尔还是需要一个基础的模板,代码如下:

import requests
import json

# 以get方法进行请求,可以直接把参数附在后面,也可以传入参数进行
response=requests.get(f"http://XXXXX/anyq?question={
      
      question}")
param={
    
    "question":question}
res = requests.get(url='https://b.faloo.com/l/0/1.html',params=param)
# 这里形参为params


# 如果是post,可以以data形式作为参数进行
params = {
    
    "username": self.username,"email": self.email, "password": self.password}
response = requests.post(request_url, data=params)
# 这里形参为data

# 如果返回的数据是unicode编码,例如
"""
"answer\":\"\u8bb2\u8bdd\u4ea4\u6d41\u6700\u5c11\u76f8\u96941\u7c73\uff0c\u6700\u597d2\u7c73\u3002 
\u4e00\u822c\u60c5\u51b5\u4e0b\uff0c\u98de\u6cab\u4f20\u64ad\u53ea\u6709\u4e0e\u4f20\u67d3\u6
e90\u8fd1\u8ddd\u79bb\u63a5\u89e6\u65f6\u624d\u53ef\u80fd\u5b9e\u73b0\u3002\u98de\u6cab
"""

# 参考 https://www.cnblogs.com/573734817pc/p/10855147.html  进行解码
decode_rs=response.text.encode("utf-8").decode('unicode_escape')

# 如果以json格式返回,直接使用json解析,而不是text
json_rs=response.json()
print(json_rs)

猜你喜欢

转载自blog.csdn.net/Castlehe/article/details/121264061
今日推荐