我尝试使用python将有关API流量的信息保存到CSV文件。
我希望数据位于csv输出中的标记名称下面。这是每10分钟循环一次,因为我想获得特定道路伸展有多糟糕的图表/历史数据。
基本上看起来像这样,
Traffic Delay - Length In Meters - Departure Time - etc
Data at 0time - Data at 0time - Data at 0time - etc
Data at10time - Data at10time - Data at10time - etc
在此示例中,标题是交通行程时间,以米为单位的长度,出发时间和以秒为单位的交通延误。 我目前正在使用的脚本如下。我已经开始为标题制作一个单独的字典,但我正在奋斗的城镇正确地整理它。任何蟒蛇大师能指导这个noobie吗?
from lxml import etree
import urllib.request
import csv
import time
#append to list next
def handleSummary(summary):
tagsOfInterest=["noTrafficTravelTimeInSeconds", "lengthInMeters", "departureTime", "trafficDelayInSeconds"] # whatever
#list to use for data analysis
global data
global header
header = tagsOfInterest
data = []
#create header dictionary that includes the data to be appended within it. IE, Header = {TrafficDelay[data(0)]...etc
for child in summary:
if 'summary' in child.tag:
for elem in child:
for item in tagsOfInterest:
if item in elem.tag:
data.append(elem.text)
#Parse the xml
def parseXML(xmlFile):
while True:
with urllib.request.urlopen("https://api.tomtom.com/routing/1/calculateRoute/-37.79205923474775,145.03010268799338:-37.798883995180496,145.03040309540322:-37.807106781970354,145.02895470253526:-37.80320743019992,145.01021142594075:-37.7999012967757,144.99318476311566:?routeType=shortest&key=notakey&computeTravelTimeFor=all") as fobj:
xml = fobj.read()
root = etree.fromstring(xml)
for child in root:
if 'route' in child.tag:
handleSummary(child)
# Write CSV file
with open('datafile.csv', 'a') as fp:
writer = csv.writer(fp, delimiter=' ')
# writer.writerow(["your", "header", "foo"]) # write header
writer.writerow(data)
with open('datafile.csv', 'r') as fp:
reader = csv.reader(fp, quotechar='"')
# next(reader, None) # skip the headers
data_read = [row for row in reader]
print(data_read)
time.sleep(600)
if __name__ == "__main__":
parseXML("xmlFile")
谢谢Stack!