【发布时间】:2015-04-17 16:39:41
【问题描述】:
我的代码的问题是没有保存在 csv 存档中,创建一个 csv 但为空白。使用打印功能显示结果,但不保存在 csv 中。
import csv
import urllib2
from bs4 import BeautifulSoup
url = "html"
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)
for tr in soup.find_all('tr')[2:]:
tds = tr.find_all('h2')
td2 = tr.find_all('th')
hora = tds[0].text.encode('utf-8')
nombre = td2[0].text.encode('utf-8')
print hora, nombre
f = csv.writer(open("prueba.csv", "w"))
f.writerow(["Hora", "Nombre"])
f.writerow([hora, nombre])
【问题讨论】:
-
我运行了代码,它对我有用。确保
soup.find_all('tr')[2:]不为空。 -
所以它节省了一些东西?你得到的csv的内容是什么?
标签: python csv beautifulsoup