# -*- coding:utf-8 -*-
import re
import urllib
import os
#得到网页源代码
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def callbackfunc(blocknum, blocksize, totalsize):
'''回调函数
@blocknum: 已经下载的数据块
@blocksize: 数据块的大小
@totalsize: 远程文件的大小
'''
percent = 100.0 * blocknum * blocksize / totalsize
if percent > 100:
percent = 100
print "%.2f%%"% percent
#下载图片
def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext' #正则表达式解析图片文件格式
imgre = re.compile(reg) #re.compile() 可以把正则表达式编译成一个正则表达式对象
savePath = r'/home/zjlyyq/PycharmProjects/untitled/images/'
imglist = imgre.findall(html) #re.findall() 方法读取html 中包含 imgre(正则表达式)的数据
x = 0
for imgurl in imglist:
picname = str(x) + '.jpg'
filename = os.path.join(savePath+picname) #设置保存路径
print filename
urllib.urlretrieve(imgurl, filename)
x = x + 1
html = getHtml("http://tieba.baidu.com/p/2460150866")
getImg(html)