簡體   English   中英

使用python將中文文本抓取到csv中時的編碼問題

[英]Encoding issue when scraping chinese text into csv with python

我在將中文文本抓取到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()

這是因為您嘗試通過utf-8解碼\\編碼,而應改用其他Unicode。 鏈接到頁面: http : //pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/

主頁以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 meta中都聲明它是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模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM