2015-12-01 25 views
1

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

+0

你可以打印'stations'並張貼在這裏呢?只是它看起來像 – SIslam

+0

CSV格式通常是在一行中用逗號/製表符分隔的,所以如果每一個字母都在它自己的行中,就不會有逗號。 –

回答

2

您可以使用此示例代碼

import csv 
with open('test.csv', "wb") as f: 
    writer = csv.writer(f) 
    writer.writerow(['A']) 
    writer.writerow(['B']) 

這會給你造成這樣

A 
B 

你可以通過你的價值

注意:檢查站的類型,如果這將返回str比你的值將單行,但如果這是列表循環播放列表示例代碼寫入列表CSV。

>>> list = [1,2,3,4,5] 
>>> with open('test.csv', 'wb') as f: 
...  writer = csv.writer(f) 
...  for i in list: 
...   writer.writerow([i]) 
... 
0

您可以用read_html大熊貓從HTML的GET表,並與你的情況to_csvsep='\n'保存到CSV文件:

import pandas as pd 
df_list = pd.read_html(your_html) 
df = df_list[0] 
df.to_csv('Your file', sep='\n') 
相關問題