python 获取网页编码方式实现代码

yipeiwu_com5年前Python基础

python 获取网页编码方式实现代码

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">
  </span><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">
python开发,自动化获取网页编码方式用到了chardet库,字符集检测,这个类在python2.7中没有,需要在官网上下载。
这里我下载好了chardet-2.3.0.tar.gz压缩包文件,只需要将压缩包文件解压后的chardet文件放到python安装包下的
python27/lib/site-packages/下,就可以了。</span> 

 然后import chardet

下面写了一个自动化检测的函数供检测Url连接,然后返回网页url的编码方式。

import chardet #字符集检测 
import urllib 
 
url="http://www.jd.com" 
 
 
def automatic_detect(url): 
  content=urllib.urlopen(url).read() 
  result=chardet.detect(content) 
 
  encoding=result['encoding'] 
 
  return encoding 
 
urls=['http://www.baidu.com','http://www.163.com','http://dangdang.com'] 
for url in urls: 
  print url,automatic_detect(url) 

上面用到了chardet类的detect方法,返回字典,然后取出编码方式encoding

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

Django model update的多种用法介绍

Django model update的多种用法介绍

model update常规用法 假如我们的表结构是这样的 class User(models.Model): username = models.CharField(max_le...

树莓派使用USB摄像头和motion实现监控

树莓派使用USB摄像头和motion实现监控

本文实例为大家分享了树莓派使用USB摄像头和motion实现监控的具体代码,供大家参考,具体内容如下 一、工具 1、树莓派3B 2、USB摄像头 二、操作步骤 1、安装motion...

程序员写Python时的5个坏习惯,你有几条?

很多文章都有介绍怎么写好 Python,我今天呢,相反,说说写代码时的几个坏习惯。有的习惯会让 Bug 变得隐蔽难以追踪,当然,也有的并没有错误,只是个人觉得不够优雅。 注意:示例代码在...

windows下python虚拟环境virtualenv安装和使用详解

前面介绍了python在ubuntu16.04环境下,python的虚拟环境virtualenv的安装,下面介绍在windows环境下的安装和使用。 环境信息 操作系统:windo...

浅谈使用Python变量时要避免的3个错误

Python编程中经常遇到一些莫名其妙的错误, 其实这不是语言本身的问题, 而是我们忽略了语言本身的一些特性导致的,今天就来看下使用Python变量时导致的3个不可思议的错误, 以后在编...