2

我只是想检索一个网页,但不知何故,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?

4

2 回答 2

12

当您尝试打印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')
于 2009-08-24T05:58:34.587 回答
2

您可以尝试以下方法:

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

我遇到了类似的bs4问题

于 2015-12-22T12:58:27.780 回答