Python 如何在表格中转换打印
我的代码的问题不是保存在csv存档中,而是创建一个空白的csv。使用打印功能显示结果,但不保存在csv中Python 如何在表格中转换打印,python,csv,beautifulsoup,Python,Csv,Beautifulsoup,我的代码的问题不是保存在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')
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])
1.导入csv
2.导入urllib2
3.从bs4导入BeautifulSoup
4.url=“html”
5.page=urllib2.urlopen(url.read())
6.汤=美汤(第页)
7.对于汤中的tr。查找所有('tr')[2:]:
8.tds=tr.find_all('h2')
9td2=tr.find_all('th'))
10hora=tds[0]。text.encode('utf-8')
11nombre=td2[0]。text.encode('utf-8')
12打印hora,nombre
13f=csv.writer(打开(“prueba.csv”、“w”))
14f、 writerow([“Hora”,“Nombre”])
15f、 writerow([hora,nombre])
一些建议
如果您能提供您正在使用的url,我将尝试并提供更好的解决方案。我得到的csv文件是: 霍拉,名字 《阿拉斯加与塞古拉》,23:50 23:15 原因是每次要写入文件时,都会以
w
模式打开该文件w
模式将替换文件内容(如果文件已存在)-它将截断文件,而不会附加到文件中。要附加,应使用a
:
f = csv.writer(open("prueba.csv", "a"))
另一个更好的选择是只打开文件一次,因为不需要关闭文件并反复重新打开:
import csv
import urllib2
from bs4 import BeautifulSoup
url = r"http://laguiatv.abc.es/programacion/tve-1-807.html"
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)
f = csv.writer(open("prueba.csv", "w"))
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.writerow(["Hora", "Nombre"])
f.writerow([hora, nombre])
有关打开功能,请参见:
“w”表示写入(如果文件已存在,则截断该文件),而“a”表示追加
不,我运行了代码,它对我有效。确保
soup.find_all('tr')[2:
不是空的。这样可以保存一些东西吗?您获得的csv内容是什么?
import csv
import urllib2
from bs4 import BeautifulSoup
url = r"http://laguiatv.abc.es/programacion/tve-1-807.html"
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)
f = csv.writer(open("prueba.csv", "w"))
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.writerow(["Hora", "Nombre"])
f.writerow([hora, nombre])