python处理抓取网页的判断编码

admin 2021年7月25日03:09:53评论91 views字数 555阅读1分51秒阅读模式

在开发自用爬虫过程中,有的网页是utf-8,有的是gb2312,有的是gbk,如果不加处理,采集到的都是乱码,解决的方法是将html处理成统一的utf-8

在开发自用爬虫过程中,有的网页是utf-8,有的是gb2312,有的是gbk,如果不加处理,采集到的都是乱码,解决的方法是将html处理成统一的utf-8编码

版本python2.7

#coding:utf-8
import chardet
#抓取网页html
line = "http://www.pythontab.com"
html_1 = urllib2.urlopen(line,timeout=120).read()
encoding_dict = chardet.detect(html_1)
print encoding
web_encoding = encoding_dict['encoding']
#处理,整个html就不会是乱码。
if web_encoding == 'utf-8' or web_encoding == 'UTF-8':
html = html_1
else :
html = html_1.decode('gbk','ignore').encode('utf-8')


本文始发于微信公众号(飓风网络安全):python处理抓取网页的判断编码

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2021年7月25日03:09:53
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   python处理抓取网页的判断编码https://cn-sec.com/archives/359720.html

发表评论

匿名网友 填写信息