使用 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)

如果您能够针对您的文档运行 xslt(我假设您可以(另一种方法将使这变得非常简单:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:text>Code,Source</xsl:text><xsl:text>&#xa;</xsl:text>
<xsl:apply-templates select="//Instrument"/>
</xsl:template>
<xsl:template match="Instrument">
<xsl:value-of select="Code"/>,<xsl:value-of select="Source"/><xsl:text>&#xa;</xsl:text>
</xsl:template>
</xsl:stylesheet>

请注意<xsl:text>&#xa;</xsl:text>元素的存在 - 这是插入在 CSV 中语义上很重要的换行符,但在 XML 中不是。

输出:

Code,Source
27BA1,YYY
28BA1,XXX
29BA1,XXX
30BA1,DDD

要在 Python 中运行它,我想你需要类似这个问题中建议的方法:

import lxml.etree as ET
dom = ET.parse(xml_filename)
xslt = ET.parse(xsl_filename)
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))

我不使用Python,所以我不知道这是否正确。

哎呀 - 我也忽略了提到您的 XML 文档无效 - 第 11 行和第 14 行缺少<Instrument>开头元素。将它们添加到它们所属的位置会使文档正确转换。

最新更新