python - 使用 Python 抓取 XML 文件
问题描述
我一直在尝试抓取一个 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()
解决方案
您在帖子中提供的 XML 文件无效。通过在此处粘贴文件进行检查。https://www.w3schools.com/xml/xml_validator.asp
我假设的有效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>
<Instrument>
<Code>29BA1</Code>
<Source>XXX</Source>
</Instrument>
<Instrument>
<Code>30BA1</Code>
<Source>DDD</Source>
</Instrument>
</Instruments>
</Series>
打印代码和源标签中的值。
from lxml import etree
root = etree.parse('data.xml').getroot()
instruments = root.find('Instruments')
instrument = instruments.findall('Instrument')
for grandchild in instrument:
code, source = grandchild.find('Code'), grandchild.find('Source')
print (code.text), (source.text)
推荐阅读
- react-native - Flatlist maintainVisibleContentPosition 导致 iO 立即崩溃
- node.js - 在 cmd 和 localhost 上得到了这个输出“createError is not defined”
- python - Python3 How to retrieve specific dates from a dataframe for stock using pandas
- c# - 使用 Newtonsoft 序列化模型列表
- kubernetes - 入口、重写目标、前端和 API 相同的 URL。版本 0.22.0+
- python - 如何在python中加速二维数组中的二维数组?
- javascript - 将 highcharts 图例停靠在图表的最底部
- maven - 如何用maven修复外部依赖缺失的jar?
- laravel - 我在 laravel 中的路线有问题
- java - JTable 不断将数字排序为字符串