【问题标题】:I am trying to write data into csv file after scraping the HTML table抓取 HTML 表后,我试图将数据写入 csv 文件
【发布时间】:2015-02-17 09:18:51
【问题描述】:
from bs4 import BeautifulSoup
import urllib2
from lxml.html import fromstring
import re
import csv

wiki = "http://en.wikipedia.org/wiki/List_of_Test_cricket_records"
header = {'User-Agent': 'Mozilla/5.0'} #Needed to prevent 403 error on Wikipedia
req = urllib2.Request(wiki,headers=header)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)


csv_out = open("mycsv.csv",'wb')
mywriter = csv.writer(csv_out) 

def parse_rows(rows):
 results = []
 for row in rows:
     tableheaders = row.findall('th')
    if table_headers:
        results.append(headers.get_text() for headers in table_headers])

    table_data = row.find_all('td')
    if table_data:
        results.append([data.gettext() for data in table_data])
return results

# Get table
 try:
     table = soup.find_all('table')[1]
 except AttributeError as e:
     print 'No tables found, exiting'
       # return 1

  # Get rows
 try:
    rows = table.find_all('tr')
 except AttributeError as e:
    print 'No table rows found, exiting'
     #return 1

table_data = parse_rows(rows)

# Print data
for i in table_data:
    print '\t'.join(i)

mywriter.writerow(i) csv_out.close()


UnicodeEncodeError Traceback(最近一次调用) 在 ()

---> 51 mywriter.writerow(d1)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)


我确实在 ipython 笔记本上获得了数据,但我无法确定写入 csv 文件的时间。

可能是什么错误?请帮忙

【问题讨论】:

  • 我尝试复制你的问题,但我无法——我不得不清理代码,因为缩进很乱,而你试图在倒数第二行写出的变量( d1) 没有在任何地方定义。你能发布你实际运行的代码来产生这个错误吗?
  • 是的。 d1 没有在任何地方定义。但我按照 Yannis P. 的建议写了 mywriter.writerow([s.encode("utf-8") for s in i]) 行,它奏效了。

标签: python html web-scraping beautifulsoup


【解决方案1】:

这是在 python 中写入 csv 的一个已知问题。您可以看到解决方案here。在你的情况下,这一切都归结为写作:

mywriter.writerow([s.encode("utf-8") for s in d1])

您也可以使用unicodecsv 库来避免这个技巧

【讨论】:

  • 谢谢亚尼斯。按照您建议的方式重写后它起作用了。
  • @Maria 也通过勾选正确答案来帮助其他用户
  • 当然。我是 StackOver 流的新手。很高兴它提供了这些功能
猜你喜欢
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 2011-12-30
  • 2019-07-20
  • 2017-05-21
  • 1970-01-01
相关资源
最近更新 更多