与1的区别在于加入了构造函数
# 封装接口请求 import requests import json class RunMain: def __init__(self, url, method, data=None): self.res = self.run_main(url, method, data) def send_get(self, url, para): res = requests.get(url, para) return res.json() def send_post(self, url, data): res = requests.post(url, data) r = res.json() return json.dumps(r, indent=2, sort_keys=True, ensure_ascii=False) def run_main(self, url, method, data=None): res = None if method.upper() == "GET": res = self.send_get(url, data) elif method.upper() == "POST": res = self.send_post(url, data) else: print("请输入正确的参数") return res if __name__ == "__main__": url = "http://apis.juhe.cn/rubbish/search" data = {"key": "6d9cc6b16d6cf63caded401b99c7311e", "q": "奶茶", "type": 2} r = RunMain(url, "post", data) print(r.res)
来源:https://www.cnblogs.com/come202011/p/12313103.html