【问题标题】:How convert print in table csv beautiful soup如何在表格csv美丽汤中转换打印
【发布时间】: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


【解决方案1】:

我得到的 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])

请参阅documentation 了解open 函数:

'w' 用于写入(如果文件已存在则截断),'a' 用于追加

【讨论】:

    【解决方案2】:
    1.导入csv 2.导入urllib2 3.从bs4导入BeautifulSoup 4. url = "html" 5. page = urllib2.urlopen(url).read() 6.汤=BeautifulSoup(页面) 7. for tr in soup.find_all('tr')[2:]: 8. tds = tr.find_all('h2') 9. td2 = tr.find_all('th') 10. hora = tds[0].text.encode('utf-8') 11. nombre = td2[0].text.encode('utf-8') 12. print hora, nombre 13. f = csv.writer(open("prueba.csv", "w")) 14. f.writerow(["Hora", "Nombre"]) 15. f.writerow([hora, nombre])

    一些建议。

    1. 在第 4 行,我希望你把“html”仅仅用于演示,因为你需要一个 url
    2. 尝试将第 13 行放在第 7 行之前,以防止多个文件访问,这可能会导致错误。

    如果您能提供您正在使用的网址,我会尝试并提供更好的解决方案。

    【讨论】:

    • 没有
      , , ?
    猜你喜欢
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2015-08-18
    相关资源
    最近更新 更多