我对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')
靓汤4.1.0will automatically convert attribute values from UTF-8,解决了这个问题:
要在方法中传递unicode:
注意标题值前面的^{} unicode literal marker 。您确实需要specify an encoding on your source file才能使其工作(文件顶部的
^{pr2}$coding
注释),或者改为使用unicode转义码:在内部,beauthulsoup使用unicode,但是您将传递给它一个包含非ascii字符的字节字符串。beauthulsoup试图为您解码为unicode,但失败了,因为它不知道您使用了什么编码。通过为它提供现成的unicode,您可以回避这个问题。在
工作示例:
相关问题 更多 >
编程相关推荐