Skip to main content
 首页 » 编程设计

python之使用 Python 抓取 XML 文件

2025年05月04日21zengkefu

我一直在尝试抓取 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> 

打印 Code 和 Source 标签中的值。

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)