Mar*_*tin 4 python encoding screen-scraping beautifulsoup
使用BeautifulSoup 3.1.0.1和Python 2.5.2,并尝试用法语解析网页.但是,一旦我调用findAll,我就会收到以下错误:
UnicodeEncodeError:'ascii'编解码器无法对位置1146中的字符u'\ xe9'进行编码:序数不在范围内(128)
以下是我目前正在运行的代码:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("http://fr.encarta.msn.com/encyclopedia_761561798/Paris.html")
soup = BeautifulSoup(page, fromEncoding="latin1")
r = soup.findAll("table")
print r
Run Code Online (Sandbox Code Playgroud)
有人知道为什么吗?
谢谢!
更新:如果被请求,下面是完整的回溯
Traceback (most recent call last):
File "[...]\test.py", line 6, in <module>
print r
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1146-1147: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
小智 11
这是另一个想法.您的终端无法显示Python的unicode字符串.解释器首先尝试将其转换为ASCII.您应该在打印之前明确编码它.我不知道确切的语义soup.findAll()
.但它可能是这样的:
for t in soup.findAll("table"):
print t.encode('latin1')
Run Code Online (Sandbox Code Playgroud)
如果t
真的是一个字符串.也许它只是另一个对象,您必须从中构建要显示的数据.