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

(编辑:jimmy 日期: 2025/3/13 浏览:2)

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

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

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。