2014-11-24 85 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