2014-11-24 87 views
0

隨着Martijn的驚人幫助,我在我的python程序中遇到了這個問題。但是,我試圖將我的單元格的內容導出到csv文件。我成功地導入,但我resuit如下:Python:使用BeautifulSoup將內容保存爲CSV

import urllib2 

from bs4 import BeautifulSoup 

soup = BeautifulSoup(urllib2.urlopen('https://clinicaltrials.gov/ct2/show/study/NCT01718158?term=NCT01718158&rank=1&show_locs=Y#locn').read()) 

import csv 

filename = 'Trial1.csv' 

f = open(filename, 'wb') 

with f: 
writer = csv.writer(f) 
for row in soup('table')[5].findAll('tr'): 
    tds = row('td') 
    result = u' '.join([cell.string for cell in tds if cell.string]) 
    writer.writerow(result) 
    print result 
f.close() 

結果:|百靈| O |代替3

| | H | N | 1 | 2約翰| 123 |爲每個特定的細胞。 我該如何糾正這一點。謝謝。

+0

我沒有一個直接的答案,但是當你在等待的時候,你爲什麼不打印tds,並且將列表理解重寫爲一個循環,因此你可以打印每個cell.string。這就是我要如何調試它... – GreenAsJade 2014-11-24 23:13:59

+1

感謝GreenAsJade的幫助。 – 2014-12-02 18:48:28

回答

0

好這個問題是你的細胞TDS包含,但有的沒有,其中作者弄糊塗了。如您所知,它是csv作家(逗號分隔值)。

總之,只要改變定界符應該糾正你的問題,像這樣的:

... 
# I'd suggest using with ... as f as in 1 line 
with open(filename, 'wb') as f: 
    # set the delimiter to \t tab than comma 
    writer = csv.writer(f, delimiter='\t') 
    for row in soup('table')[5].findAll('tr'): 
     tds = row('td') 
     # you can writerow the list directly as it will convert it to string for you 
     writer.writerow([cell.string for cell in tds if cell.string]) 
... 

希望這有助於。

+0

它工作!感謝百萬Anzel。對不起,我沒有在假期回到這裏。非常感謝你的幫助。 – 2014-12-02 18:47:46