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

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

相关文章

Python常用算法学习基础教程

Python常用算法学习基础教程

本节内容 算法定义 时间复杂度 空间复杂度 常用算法实例 1.算法定义 算法(Algorithm)是指解题方案的准确而完整的描述,是一系列解决问题的清晰指令,算法代表着用系统的方法描...

通过python+selenium3实现浏览器刷简书文章阅读量

准备工作 下载python,本文以python3.6为例。python3.6下载地址:python3下载地址,选择合适的版本安装。安装成功后,打开命令提示符,在其中输入python,显示...

Python实现在线暴力破解邮箱账号密码功能示例【测试可用】

本文实例讲述了Python实现在线暴力破解邮箱账号密码功能。分享给大家供大家参考,具体如下: dic 字典格式如下(mail.txt) : username@gmail.com:pa...

Pytorch实现神经网络的分类方式

本文用于利用Pytorch实现神经网络的分类!!! 1.训练神经网络分类模型 import torch from torch.autograd import Variable imp...

CentOS安装pillow报错的解决方法

安装pillow出现以下问题: ValueError: jpeg is required unless explicitly disabled using --disable-jpe...