【发布时间】:2018-11-23 22:48:15
【问题描述】:
我一直在尝试抓取 XML 文件以从 2 个标签(仅代码和源代码)中复制内容。 xml 文件如下所示:
<Series xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RunDate>2018-06-12</RunDate>
<Instruments>
<Instrument>
<Code>27BA1</Code>
<Source>YYY</Source>
</Instrument>
<Instrument>
<Code>28BA1</Code>
<Source>XXX</Source>
</Instrument>
<Code>29BA1</Code>
<Source>XXX</Source>
</Instrument>
<Code>30BA1</Code>
<Source>DDD</Source>
</Instrument>
</Instruments>
</Series>
我只是正确地抓取了第一个代码。下面是代码。有人可以帮忙吗?
import xml.etree.ElementTree as ET
import csv
tree = ET.parse("data.xml")
csv_fname = "data.csv"
root = tree.getroot()
f = open(csv_fname, 'w')
csvwriter = csv.writer(f)
count = 0
head = ['Code', 'Source']
csvwriter.writerow(head)
for time in root.findall('Instruments'):
row = []
job_name = time.find('Instrument').find('Code').text
row.append(job_name)
job_name_1 = time.find('Instrument').find('Source').text
row.append(job_name_1)
csvwriter.writerow(row)
f.close()
【问题讨论】: