使用chardet探测字符串编码

作者: 盗花 | 来源:发表于2018-05-13 23:48 被阅读138次

有时在使用python爬虫爬取页面时,返回的内容是乱码的,一种行之有效的方法是利用chardet(需要使用pip安装)探测字符串的编码,再相应调整爬虫的编码方式进行解码。示例如下:

1.利用requests爬取页面内容

In [86]: import requests

In [87]: r = requests.get('http://2017.ip138.com/ic.asp')

In [88]: r.text
Out[88]: '<html>\r\n<head>\r\n<meta http-equiv="content-type" content="text/html; charset=gb2312">\r\n<title> ÄúµÄIPµØÖ· </title>\r\n</head>\r\n<body style="margin:0px"><center>ÄúµÄIPÊÇ£º[XX.XX.XX.XX] À´×Ô£º±±¾©Êб±¾©ÊÐ Åô²©Ê¿¿í´ø</center></body></html>'

In [89]: r.content
Out[89]: b'<html>\r\n<head>\r\n<meta http-equiv="content-type" content="text/html; charset=gb2312">\r\n<title> \xc4\xfa\xb5\xc4IP\xb5\xd8\xd6\xb7 </title>\r\n</head>\r\n<body style="margin:0px"><center>\xc4\xfa\xb5\xc4IP\xca\xc7\xa3\xba[XX.XX.XX.XX] \xc0\xb4\xd7\xd4\xa3\xba\xb1\xb1\xbe\xa9\xca\xd0\xb1\xb1\xbe\xa9\xca\xd0 \xc5\xf4\xb2\xa9\xca\xbf\xbf\xed\xb4\xf8</center></body></html>'

此时可以看到,r.text的内容为乱码,r.content的内容为字节码,说明该爬虫默认的编码不能解码此页面的内容。查看爬虫的默认编码方式如下:

In [90]: r.encoding
Out[90]: 'ISO-8859-1'

2.利用chardet探测字符串编码
现在我们先探测爬取的页面的编码方式:

In [91]: import chardet

In [92]: chardet.detect(r.content)
Out[92]: {'confidence': 0.99, 'encoding': 'GB2312', 'language': 'Chinese'}  # 说明页面的编码方式为GB2312

修改爬虫的编码方式,再次查看页面内容

In [93]: r.encoding = chardet.detect(r.content)['encoding']

In [94]: r.text
Out[94]: '<html>\r\n<head>\r\n<meta http-equiv="content-type" content="text/html; charset=gb2312">\r\n<title> 您的IP地址 </title>\r\n</head>\r\n<body style="margin:0px"><center>您的IP是:[XX.XX.XX.XX] 来自:北京市北京市 XX</center></body></html>'

可以看到,修改了爬虫的编码方式后,能够正确显示页面内容了。

总结:chardet是一个优秀的字符串/文件编码检测模块,能够成为爬虫的常备工具箱之一。

备注:感谢@Python雁横的提醒,使用r.encoding = r.apparent_encoding即可方便的解决问题。因为r.apparent_encoding就使用了chardet的库。如下所示:

In [41]: r.apparent_encoding?
Type:        property
String form: <property object at 0x1101bf638>
Docstring:   The apparent encoding, provided by the chardet library.

相关文章

网友评论

    本文标题:使用chardet探测字符串编码

    本文链接:https://www.haomeiwen.com/subject/kovrdftx.html