python爬虫(三)

简单粗暴的方法:获得网页编码

获得服务器头部的header信息,获取网页返回的声明编码

有时有结果,有时候结果是none的原因


使用第三方专业模块 chardet自动化

chardet:一个自动化判断网页编码的python第三方库,下载chardet,安装使用,开始字符集检测,封装成函数,可以复用

把chardet下载到python的lib\site-package

import urllib
import chardet

url = "http://www.163.com"
html = urllib.urlopen(url)
info = html.info()
content = html.read()
print chardet.detect(content)

###output
{'confidence': 0.99, 'language': 'Chinese', 'encoding': 'GB2312'}
[Finished in 4.2s]

封装成函数 检查获取编码方式

def automatic_detect(url):
	content = urllib.urlopen(url).read()
	result = chardet.detect(content)
	encoding = result['encoding']
	return encoding


urls = ["http://www.163.com","http://www.jd.com","http://www.baidu.com"]

for url in urls:
	print url,automatic_detect(url)


http://www.163.com GB2312
http://www.jd.com utf-8
http://www.baidu.com utf-8
[Finished in 5.6s]



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值