利用API抓取数据入库

it2022-05-05  129

import datetime import json import re import time from threading import Timer

import requests import pymysql db = pymysql.connect(“000000000”, “root”, “xxxxx”, “xxxx”) cursor = db.cursor()

def print_time(): while True: print(‘Job1-startTime:%s’ % (datetime.datetime.now().strftime(’%Y-%m-%d %H:%M:%S’))) w = time.time() url = “xxxxxxxxxxxxxxxxx” headers = {‘Content-Type’: ‘application/json’} parm = { “command”: “xxxxxxxxxxxxxxxxx”, “switch_ip”: “ip” }

red = requests.post(url, headers=headers, json=parm) red = red.content.decode() data = json.loads(red) hello = data['Data']['config'] s = hello.splitlines() x = [] for d in s: if "Output:" and "bytes" in d: s = re.findall("\d+", d)[0] x.append(s) y = x[0] d = x[1] k = time.time() insert_switch = ("INSERT INTO NB(input,output,time)" "VALUES(%s,%s,%s)") data_switch = (y, d, k) cursor.execute(insert_switch, data_switch) db.commit() print(y, d, k) r = time.time() - w slp = 60 - r time.sleep(slp) print('Job1-endTime:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) print('------------------------------------------------------------------------')

def main(): # ip = str(input(“请输入交换机IP:”)) # time_start = int(input(“请输入多久后执行(单位/秒):”)) print_time() Timer(time_start, print_time, ).start() db.close()

if name == ‘main’: main()


最新回复(0)