简体   繁体   English

使用ElementTree解析XML会生成空的csv文件

[英]Using ElementTree to parse XML results in empty csv file

I'm a complete beginner in Python, so I've had to rely on several tutorials to put this code together. 我是Python的完全入门者,所以我不得不依靠一些教程来将这些代码放在一起。 It does produce a .csv file, but it turns out empty (0kb). 它确实生成一个.csv文件,但结果为空(0kb)。 I've found others with this question had forgotten to close the file, but that doesn't seem to be the problem here. 我发现其他有此问题的人都忘记了关闭文件,但这似乎不是这里的问题。 I'm grateful for any hints. 我很感谢任何提示。

This is the xml if that helps: https://api.nextbike.net/maps/nextbike-live.xml?city=14 这是xml,如果有帮助的话: https : //api.nextbike.net/maps/nextbike-live.xml?city=14

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('nextbike-live.xml')
root = tree.getroot()

with open('Bike_pos.csv', 'w') as Bike_pos:
    csvwriter = csv.writer(Bike_pos)
    bike_head = []

    count = 0
    for member in root.findall('place'):
        bike = []
        if count == 0:
            station = member.find('name').tag
            bike_head.append(station)
            lat = member.find('lat').tag
            bike_head.append(lat)
            lon = member.find('lng').tag
            bike_head.append(lon)
            bikeno = member.find('bike_numbers').tag
            bike_head.append(bikeno)
            count = count + 1

        station = member.find('name').text
        bike.append(station)
        lat = member.find('lat').text
        bike.append(lat)
        lon = member.find('lng').text
        bike.append(lon)
        bikeno = member.find('bike_numbers').text
        csvwriter.writerow(bike)
Bike_pos.close()

I got help from a good friend. 我得到了一个好朋友的帮助。 My xml source file had several children that my code wasn't searching. 我的xml源文件有几个孩子,我的代码没有搜索到。

He gave me this code that worked like a charm and is a lot simpler than what I had: 他给了我这段代码,它像一个魅力一样工作,比我拥有的代码简单得多:

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('nextbike-live-test.xml')
root = tree.getroot()

with open('Bike_pos.csv', 'w') as Bike_pos:
    csvwriter = csv.writer(Bike_pos)

    #CSV Header
    csvwriter.writerow(['Station', 'lat', 'lng', 'Bikes'])

    #Add info about each station
    for country in root.findall('country'):
        for city in country.findall('city'):
            for place in city.findall('place'):
                bike = []

                bike.append(place.get('name'))
                bike.append(place.get('lat'))
                bike.append(place.get('lng'))
                bike.append(place.get('bike_numbers'))
                csvwriter.writerow(bike)

To make it simpler you can try like this as well: 为了简化起见,您也可以这样尝试:

import requests
import csv
from lxml.html import fromstring

with open("Bike_Details.csv","w",newline="") as infile:
    writer = csv.writer(infile)
    writer.writerow(["station","lat","lng","bike_num"])

    res = requests.get("https://api.nextbike.net/maps/nextbike-live.xml?city=14")
    root = fromstring(res.content)
    for items in root.cssselect("country city place"):
        station = items.get("name")
        lat = items.get("lat")
        lng = items.get("lng")
        bike_num = items.get("bike_numbers")
        print(station,lat,lng,bike_num)
        writer.writerow([station,lat,lng,bike_num])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM