功能描述:
调用第三方接口获取数据,并写入excel中。
用到了在Python中读取和写入excel,如何调用http接口,如何对接口返回json处理。
代码:
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import time
import json
import requests
from openpyxl.reader.excel import load_workbook
#初始化数值
access_token = 'xxxx'
file_name = 'D:/test/test.xlsx'
file_name_result = 'D:/test/test-resu.txt'
file_name_except = 'D:/test/test-except.txt'
#记录下token
token_list = []
token_list.append(access_token)
#获取接口信息
def getinfo(CAR_ID,i):
global access_token
try:
url = "http://192.168.1.1:8000/xxxxxx"
headers = {
"Content-Type": "application/json;charset=utf-8"}
params = {
"access_token":access_token}
body = {
"SID":"xx001",
"CAR_ID":CAR_ID}
r = requests.post(url, params=params, data=json.dumps(body), headers=headers)
#print("获取返回的状态码", r.status_code)
json_r = r.json()
#print("json类型转化成python数据类型", json_r)
# 转换成字典格式
d = json.loads(r.text)
# 从字典里取 data 数组
dataList = d.get('data')
if d.get('code') != 200:
url = "http://192.168.1.1:8000/xxxxxx/oauth2/token"
headers = {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"}
body = {
"grant": "client1",
"client": "xxxxxxxx"}
r = requests.post(url, data=body, headers=headers)
d = json.loads(r.text)
dataList = d.get('custom')
access_token = dataList['access_token']
url = "http://192.168.1.1:8000/xxxxxx/xxxxx"
headers = {
"Content-Type": "application/json;charset=utf-8"}
params = {
"access_token": access_token}
body = {
"SID": "xx001",
"CAR_ID":CAR_ID}
r = requests.post(url, params=params, data=json.dumps(body), headers=headers)
d = json.loads(r.text)
dataList = d.get('data')
#此部分根据接口返回参数修改,如下是例子
CAR_ID= dataList[0][0]['ID']
DM = dataList[0][0]['DM']
XX = dataList[0][0]['XX']
YY = dataList[0][0]['YY']
#组合成list
list = [ID, DM,XX,YY]
#print("请求成功!", CAR_ID,"第",i,"行")
except BaseException as e:
print("请求失败!", str(e),CAR_ID,"第",i,"行")
list = [ID,'','','']
return list
startdatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 打开xls文件
wb = load_workbook(file_name)
# 获取所有表格(worksheet)的名字
sheets = wb.get_sheet_names()
# 第一个表格的名称
sheet_first = sheets[0]
#获取特定的worksheet
ws = wb.get_sheet_by_name(sheet_first)
# 获取表的行数
rows = ws.max_row
cols = ws.max_column
for i in range(rows+1): # 循环逐行遍历
if i < 1:
continue
else:
CAR_ID = ws.cell(row=i, column=1).value
list = getinfo(CAR_ID,i)
#access_token = getinfo.token
#写文件
try:
file = open(file_name_result, 'a')
s = str(list).replace('[', '').replace(']', '') # 去除[],这两行按数据不同,可以选择
s = s.replace(' ', '').replace("'", '') + '\n' # 去除单引号,逗号,每行末尾追加换行符
file.write(s)
file.close()
print("写入成功!", CAR_ID, "第", i, "行")
except BaseException as e:
print("写入失败!", str(e), CAR_ID, "第", i, "行")
file = open(file_name_except, 'a')
file.write("第"+str(i)+"行:"+CAR_ID+str(e)+'\n')
file.close()
pass
continue
enddatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
token_list.append(access_token)
print("使用的token",token_list)
print(file_name,"执行完成!开始时间:",startdatetime,"结束时间:",enddatetime)