urlopen,BeautifulSoup和UTF-8问题

时间:2009-08-24 05:17:24

标签: python utf-8 urllib2 beautifulsoup

我只是想检索一个网页,但不知何故,HTML文件中嵌入了一个外来字符。使用“查看源”时,此字符不可见。

isbn = 9780141187983
url = "http://search.barnesandnoble.com/booksearch/isbninquiry.asp?ean=%s" % isbn
opener = urllib2.build_opener()
url_opener = opener.open(url)
page = url_opener.read()
html = BeautifulSoup(page) 
html #This line causes error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 21555: ordinal not in range(128)

我也试过......

html = BeautifulSoup(page.encode('utf-8'))

如何在不收到此错误的情况下将此网页读入BeautifulSoup?

2 个答案:

答案 0 :(得分:11)

当您尝试打印 BeautifulSoup文件的表示时,实际上可能会发生此错误,如果我怀疑您在交互式控制台中工作,则会自动发生。

# This code will work fine, note we are assigning the result 
# of the BeautifulSoup object to prevent it from printing immediately.
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(u'\xa0')

# This will probably show the error you saw
print soup

# And this would probably be fine
print soup.encode('utf-8')

答案 1 :(得分:1)

您可以尝试以下方法:

import codecs 
f = codecs.open(filename,'r','utf-8')
soup = BeautifulSoup(f.read(),"html.parser")

我遇到了与bs4

类似的问题