我不熟悉 beautifulsoup 的编码。
当我处理一些页面时,有些属性是中文的,我想用这个中文属性来提取标签。
例如,如下所示的 html:
<P class=img_s>
<A href="/pic/93/b67793.jpg" target="_blank" title="查看大图">
<IMG src="/pic/93/s67793.jpg">
</A>
</P>
我想提取'/pic/93/b67793.jpg' 所以我所做的是:
img_urls = form_soup.findAll('a',title='查看大图')
遇到:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb2 in position 0: ordinalnot in range(128)
为了解决这个问题,我做了两种方法,都失败了: 一种方法是:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
另一种方式是:
response = unicode(response, 'gb2312','ignore').encode('utf-8','ignore')
最佳答案
需要将unicode传入findAll方法:
# -*- coding: utf-8
...
img_urls = form_soup.findAll('a', title=u'查看大图')
注意 u
unicode literal marker在标题值前面。你确实需要 specify an encoding on your source file为此(文件顶部的 coding
注释),或改用 unicode 转义码:
img_urls = form_soup.findAll('a', title=u'\u67e5\u770b\u5927\u56fe')
在内部,BeautifulSoup 使用 unicode,但您向它传递的是一个包含非 ascii 字符的字节字符串。 BeautifulSoup 尝试为您将其解码为 unicode,但失败了,因为它不知道您使用的是什么编码。通过为它提供现成的 unicode 而不是你回避了这个问题。
工作示例:
>>> from BeautifulSoup import BeautifulSoup
>>> example = u'<P class=img_s>\n<A href="/pic/93/b67793.jpg" target="_blank" title="<A href="/pic/93/b67793.jpg" target="_blank" title="\u67e5\u770b\u5927\u56fe"><IMG src="/pic/93/s67793.jpg"></A></P>'
>>> soup = BeautifulSoup(example)
>>> soup.findAll('a', title=u'\u67e5\u770b\u5927\u56fe')
[<a href="/pic/93/b67793.jpg" target="_blank" title="查看大图"><img src="/pic/93/s67793.jpg" /></a>]
关于python - beautifulsoup中属性为中文时如何获取标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11168687/