我用BeautifulSoup來提取一個html表並將元素存儲在一個列表中。接下來,我想將列表寫入一個.csv文件,但它看起來像編寫器函數不會將元素寫入不同的行。如何使用csv_writer將列表寫入單獨的行?
import csv
from bs4 import BeautifulSoup
# Grab first table (station table in html file)
def parse_station(html):
soup = BeautifulSoup(html)
s_table = soup.find_all('table')[1]
stations = []
for tr in s_table.find_all('tr')[1:]:
td = tr.find_all('td')[1]
td = td.get_text()
stations.append(td)
return stations
stations = parse_station(open('data.html').read())
with open('stations.csv', "wb") as f:
csv_writer = csv.writer(f)
csv_writer.writerow([stations])
f.close()
該.csv像:
A,B,C,D,E
代替:
A,
B,
C,
D,
E,
這有什麼錯我的代碼?我該如何解決它? (我使用Python 2.7)
你可以打印'stations'並張貼在這裏呢?只是它看起來像 – SIslam
CSV格式通常是在一行中用逗號/製表符分隔的,所以如果每一個字母都在它自己的行中,就不會有逗號。 –