Python爬蟲_簡單獲取百度貼吧圖片

#coding=utf-8
import re
import urllib

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)
    imglist = re.findall(imgre,html)
    x = 0

    #保存文件到本地,urlretrieve函數的第一個參數是URL,第二個是地址
    for imgurl in imglist:
        print '正在保存第' + str(x+1) + '圖片...'
        urllib.urlretrieve(imgurl,'%s.jpg' % x,callbackfunc)
        x+=1
    return imglist      
   
html = getHtml("http://tieba.baidu.com/p/2460150866")
#print getImg(html)
getImg(html)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章