如何在beautifulsoup中获取属性为中文时的标签

you*_*001 1 python beautifulsoup

我不熟悉beautifulsoup的编码.

当我处理某些页面时,某些属性是中文,我想使用这个中文属性来提取标签.

例如,如下所示的html:

<P class=img_s>
<A href="/pic/93/b67793.jpg" target="_blank" title="????">
<IMG src="/pic/93/s67793.jpg">
</A>
</P>
Run Code Online (Sandbox Code Playgroud)

我想提取'/pic/93/b67793.jpg'所以我做的是:

img_urls = form_soup.findAll('a',title='????')
Run Code Online (Sandbox Code Playgroud)

遇到:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xb2 in position 0: ordinalnot in range(128)
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,我做了两个方法,都失败了:一种方法是:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")
Run Code Online (Sandbox Code Playgroud)

另一种方式是:

response = unicode(response, 'gb2312','ignore').encode('utf-8','ignore') 
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

您需要将unicode传递给findAll方法:

# -*- coding: utf-8
... 
img_urls = form_soup.findAll('a', title=u'????')
Run Code Online (Sandbox Code Playgroud)

请注意标题值前面的uunicode文字标记.您需要在源文件上指定一个编码才能使其工作(coding文件顶部的注释),或者切换到unicode转义码:

img_urls = form_soup.findAll('a', title=u'\u67e5\u770b\u5927\u56fe')
Run Code Online (Sandbox Code Playgroud)

在内部,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>]
Run Code Online (Sandbox Code Playgroud)