【问题标题】:Encoding issue when scraping chinese text into csv with python使用 python 将中文文本抓取到 csv 时的编码问题
【发布时间】:2015-12-11 14:49:57
【问题描述】:

我无法将中文文本抓取到 csv 中。我尝试了 3 种不同的东西(在代码中注释),但 csv 仍然只包含乱码。

from bs4 import BeautifulSoup
import urllib2
#import codecs

url="http://v.youku.com/v_show/id_XOTU2Nzc3NDYw.html"
page = urllib2.urlopen(url,context=gcontext).read()#.decode('utf-8', 'ignore')
soup = BeautifulSoup(page)
title= soup.findAll('h1', { "class" : "title" })[0].string#.encode('utf-8')
outputfile='.../file.csv'
fd = open(outputfile,'a')
#fd = codecs.open(outputfile, "a", "utf-8")    
fd.write(title)
fd.close()

【问题讨论】:

  • 你应该说出什么给了urllib2.urlopen(url,context=gcontext).headers.get('content_type')。它应该提供有关实际页面编码的提示。

标签: python encoding beautifulsoup


【解决方案1】:

主页采用 utf8 编码。我可以这样加载它:

>>> url="http://v.youku.com/v_show/id_XOTU2Nzc3NDYw.html"
>>> page = urllib2.urlopen(url)
>>> page.headers.get('content-type')
'text/html; charset=UTF-8'
>>> txt = page.read().decode('utf8')
>>> print txt

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
...

因此它在 HTTP 级别和 html 元数据中都声明它是 utf8 编码的,并且似乎在 utf8 中解码得很好。

我更进一步:

>>> soup = BeautifulSoup(txt)
>>> title= soup.findAll('h1', { "class" : "title" })[0].string.encode('utf-8')
>>> print repr(title)
'\n\t\t\xe8\xa7\x86\xe9\xa2\x91: \xe3\x80\x90\xe9\xac\xbc\xe9\x97\x95\xe4\xb8\x83\xe7\x9a\x87\xe3\x80\x91\xe5\x90\x84\xe5\x9b\xbd\xe8\xb7\x91\xe9\x85\xb7\xe9\xab\x98\xe6\x89\x8b\xe6\x9e\x81\xe9\x99\x90\xe8\xb7\x91\xe9\x85\xb7\xe6\xb7\xb7\xe5\x89\xaa'

所以title 是一个完全正确的 utf8 编码字节字符串,因为我可以打印它并且它给出了中文字符。

如果文件似乎包含垃圾,那只是因为您使用不支持 utf8 的编辑器打开它,或者忘记将其置于 utf8 模式。

【讨论】:

  • 你是对的。我用 Excel 打开了 csv,我认为默认情况下会正确读取 utf8,但它没有。谢谢..
【解决方案2】:
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 2013-04-18
  • 1970-01-01
  • 2019-01-31
  • 2017-11-14
  • 2019-03-24
  • 2019-05-18
相关资源
最近更新 更多