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编写脚本获取手机当前应用apk的信息

前提是已设置ANDROID_HOME环境变量,使用aapt工具获取apk的信息,保存至脚本所在目录下的PackageInfo.txt文件中: import os import te...

python字符串查找函数的用法详解

python字符串查找函数的用法详解

python字符串查找函数的使用 打开Python开发工具IDLE,新建‘findstr.py'文件,并写代码如下: s ='/ab/bx,.s' print (s.find('/x...

python matplotlib 在指定的两个点之间连线方法

python matplotlib 在指定的两个点之间连线方法

为了找到matplotlib在两个点之间连线的方法真是费了好大功夫,最后还是决定用简单的 plt.plot 来解决。如果有好多对点,则可以通过循环实现连接,还可以用 plt.arrow...

Django视图扩展类知识点详解

扩展类必须配合GenericAPIView使用扩展类内部的方法,在调用序列化器时,都是使用get_serializer 需要自定义get、post等请求方法,内部实现调用扩展类对应方法即...

在Pytorch中使用样本权重(sample_weight)的正确方法

step: 1.将标签转换为one-hot形式。 2.将每一个one-hot标签中的1改为预设样本权重的值 即可在Pytorch中使用样本权重。 eg: 对于单个样本:loss = -...