微信公众号:[技术清点]
关注可了解更多信息。问题或建议,请公众号留言;
说明
使用python请求http接口
GET 请求
注:发送请求,模似请求头,浏览器信息查看,google上打开标签,输入about:version即可
def get(self, url, param=None, headers=None, cookies=None):
res = None
if headers is None:
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Accept-Language": "zh-CN,zh;q=0.8",
"Cache-Control": "max-age=0",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"
}
if cookies is None:
res = requests.get(url=url, data=json.dumps(param),
headers=headers, cookies=cookies)
else:
res = requests.get(url=url, data=json.dumps(param),
headers=headers)
#print("res=>", res.text)
if res.status_code == 200:
return res.text
else:
return None
POST 请求
同理也是简单调用
def post(self, url, param=None, headers=None, cookies=None):
if headers is None:
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Accept-Language": "zh-CN,zh;q=0.8",
"Cache-Control": "max-age=0",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"
}
res = None
#print("param=",param)
#json_data = json.dumps(param,ensure_ascii=False) #.encode("utf-8")
json_data = json.dumps(param)
#print("json_data=",json_data)
if cookies is None:
res = requests.post(url=url, data=json.dumps(param),
headers=headers, cookies=cookies)
else:
res = requests.post(url=url, data=json.dumps(param),
headers=headers)
res.encoding = 'utf-8'
if res.status_code == 200:
return res.text
else:
return None
使用类封装
import requests
import json
import re
class HttpUtil:
def get(self, url, param=None, headers=None, cookies=None):
xxxx_与上相同
def post(self, url, param=None, headers=None, cookies=None):
xxxx_与上相同
# 测试
def test_http(self):
url = 'http://localhost:8090/pcrm/crm/sale'
retJson = self.get(url)
#print("json:", retJson)
data = json.loads(retJson)
text = data.get("data")
#print("test=>", text)
#retData = json.loads(text)
total = text.get("total")
print("total:", total)
text2 = text.get("records")
#print("test2=>", text2)
count = 0
if text2:
for cust in text2:
count = count + 1
print("列表数据"+str(count)+":", cust)
# if html:
#调用代码
if __name__ == "__main__":
httpTest = HttpUtil()
httpTest.test_http()
###Tips
下面的是我的公众号二维码图片,欢迎关注。
图注:公众号
注: