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

2024-10-01 02:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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' 所以我所做的是:

^{pr2}$

然后遇到:

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') 

Tags: 方法in编码属性responsehtmlsys页面
2条回答

靓汤4.1.0will automatically convert attribute values from UTF-8,解决了这个问题:

要在方法中传递unicode:

# -*- coding: utf-8
... 
img_urls = form_soup.findAll('a', title=u'查看大图')

注意标题值前面的^{} unicode literal marker。您确实需要specify an encoding on your source file才能使其工作(文件顶部的coding注释),或者改为使用unicode转义码:

^{pr2}$

在内部,beauthulsoup使用unicode,但是您将传递给它一个包含非ascii字符的字节字符串。beauthulsoup试图为您解码为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>]

相关问题 更多 >