zoukankan      html  css  js  c++  java
  • python抓取中文网页乱码

    我们经常通过python做采集网页数据的时候,会碰到一些乱码问题,今天给大家分享一个解决网页乱码,尤其是中文网页的通用方法。

    首页我们需要安装chardet模块,这个可以通过easy_install 或者pip来安装。

    安装完以后我们在控制台上导入模块,如果正常就可以。

    比如我们遇到的一些ISO-8859-2也是可以通过下面的方法解决的。

    直接上代码吧:

    import urllib2
    import sys
    import chardet

    req = urllib2.Request("http://www.163.com/")##这里可以换成http://www.baidu.com,http://www.sohu.com
    content = urllib2.urlopen(req).read()
    typeEncode = sys.getfilesystemencoding()##系统默认编码
    infoencode = chardet.detect(content).get('encoding','utf-8')##通过第3方模块来自动提取网页的编码
    html = content.decode(infoencode,'ignore').encode(typeEncode)##先转换成unicode编码,然后转换系统编码输出
    print html

     通过上面的代码,相信能够解决你采集乱码的问题。

  • 相关阅读:
    RESTful规范1
    Django -- 发送HTML格式的邮件
    11.10 vue
    Selenium 使用
    Beautiful Soup的用法
    Pthon常用模块之requests,urllib和re
    爬虫--工具安装Jupyter anaconda
    11-3
    Python -- tabulate 模块,
    Python -- queue队列模块
  • 原文地址:https://www.cnblogs.com/wanpython/p/3117957.html
Copyright © 2011-2022 走看看