简体   繁体   中英

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. It does produce a .csv file, but it turns out empty (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

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.

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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