Python爬虫urllib笔记(一)

#-*-coding:utf-8-*-

import urllib

url="http://www.163.com/"

htlm=urllib.urlopen(url)

#所有gb2312全部写成gbk这样都不会乱码
#print htlm.read().decode("gbk").encode("utf-8")
#查看头信息
# print htlm.info()
# 查看状态码
#print htlm.getcode()
"""
常见HTTP状态码
200正常访问301重定向
404网页不存在403禁止访问
500服务器忙出现问题
参考:HTTP权威指南--介绍http协议
"""
# 查看传入url
# print htlm.geturl()
# 
# 关闭连接
# htlm.close()

#网页抓取,下载网页
# urllib.urlretrieve(url,"F:\\data\\pachong\\pa1.htlm")

# htlm.close()
# "ignore"忽略不能转换的字符
print htlm.read().decode("gbk","ignore").encode("utf-8")


#-*-coding:utf-8-*-

import urllib

url="http://www.163.com/"

htlm=urllib.urlopen(url)

code=htlm.getcode()

#网页抓取,下载网页
if code==200:
	print htlm.read().decode("gbk","ignore").encode("utf-8")
	print htlm.info()
else:
	print "404"

#-*-coding:utf-8-*-

import urllib

"""
urlretrieve函数参数说明
1传入参数,类型字符串
2传入的本地路径及文件名
3函数的调用--保证函数有3个参数
(1)到目前为止传递的数据块的数量
(2)每个数据块的大小,单位byte 字节
(3)远程文件的大小(有时候返回-1)
"""

#带进度条的爬虫
def callback(a,b,c):
	"""
	@a:是到目前为止传递的数据块的数量
	@b:是每个数据块的大小,单位byte 字节
	@c:是远程文件的大小(有时候返回-1)
	"""
	down_progress=100.0*a*b/c


	if down_progress>100:
		down_progress=100
	#,可以使输出数据在一行显示	
	print "%.2f%%" % down_progress,

url="http://www.iplaypython.com/"
local="F:\\data\\pachong\\pa2.html"

urllib.urlretrieve(url,local,callback)


#-*-coding:utf-8-*-

# import urllib

# url="http://www.iplaypython.com/"
# info=urllib.urlopen(url).info()
# print info
# # 获取http头信息里的编码--有些网站没有声明编码
# print info.getparam('charset')
# 
# import urllib
# # 第三方模块 http头获取不到编码-使用第三方类库获取编码
# import chardet  #字符串检测
# url="http://www.iplaypython.com/"
# content=urllib.urlopen(url).read()
# result=chardet.detect(content)
# print result['encoding']


import urllib
import chardet 
#封装成函数-自动识别网站编码
def automatic_detect(url):
	content=urllib.urlopen(url).read()
	result=chardet.detect(content)
	encoding=result['encoding']
	return encoding

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

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





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值