python:多線程爬蟲(美女照片)

上編剛剛寫的py,,而進度條不是很滿意,而且 是單線程,所以修改爲多線程,如果網絡快,5分鐘全部下載完全,該網站併發不好,而且經常訪問不了,出現失敗很正常。

只是學習py爬蟲吧了。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from os import path,makedirs
import re
from threading import Thread
from datetime import datetime
def trypicdir(picpath):
    if not path.exists(picpath):     #下載到的本地目錄,路徑不存在時創建一個
        makedirs(picpath)

#顯示下載進度
def schedule(a,b,c):
    '''''
    a:已經下載的數據塊
    b:數據塊的大小
    c:遠程文件的大小
    '''
    per = 100.0 * a * b / c
    if per > 100 :
        per = 100
    #print ('%.2f%%' % per)
    print ('%.2f%%' % per),

#獲取html源碼
def getHtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html
#正則匹配分頁
def findPage(html):
    myItems = re.findall('<span>(\d*)</span>', html, re.S)
    if myItems :
        return myItems.pop()
    else:
        return 0
#正則匹配列表
def findList(html):
    Items = re.findall('<span><a href="http://www.mzitu.com/(\d*)" target="_blank">(.*?)</a></span>', html, re.S)
    myItems=[]
    for i in Items:
        myItems.append((i[0]))
    return myItems

#下載圖片
def downloadImg(url_pic,picpath):
    tmppic = re.findall("http:\/\/www.mzitu.com/(.*?)$",url_pic,re.S)[0]
    picfile = picpath+'/%s.jpg' % '_'.join(tmppic.split('/'))
    html=getHtml(url_pic)
    myItems = re.findall('<p><a href="http:\/\/www.mzitu.com/.*?" ><img src="(.*?)" alt=".*?" /></a></p>',html,re.S)
    print ('\n正在下載%s圖片存儲到本地%s.....'%(url_pic,picfile))
    try:
        urllib.urlretrieve(myItems[0], picfile, schedule)
    except:
        print ('下載%s圖片存儲到本地%s失敗,請檢查鏈接是否有問 '%(url_pic,picfile))

#單個美女連接下載
def getdowns(modelUrl,picpath):
    listHtml=getHtml(modelUrl)
    TotablNum=findPage(listHtml)
    if TotablNum != 0:
        for i in range(1,(int(TotablNum)+1)):
            downloadImg(url_pic='%s/%s'%(modelUrl,i),picpath=picpath)
    else:
        downloadImg(url_pic='%s'%(modelUrl),picpath=picpath)
'''
思路:
1、獲取所有美女連接列表。
2、獲取單個美女總連接數。
3、下載。
'''
if __name__ == '__main__':
    starttime=datetime.now()
    #picpath=r"F:\mypython3\9temp\9tmp_pic"
    picpath='/tmp/pic_tmp2'
    trypicdir(picpath=picpath)
    #downloadImg(url_pic='http://www.mzitu.com/80942/43',picpath=picpath)
    listHtml = getHtml('http://www.mzitu.com/model')    #這是其中一個模塊的url,可以添加不同的模塊url從而達到整站爬取。
    listContent = findList(listHtml)
    #print ("listContent:",listContent)
    #多線程使用方法
    threads = []
    for i in listContent:
        threads.append(Thread(target=getdowns,args=('http://www.mzitu.com/%s'%i,picpath)))
    for t in threads:
        #t.setDaemon(True)
        t.start()
    '''
    #單線程使用方法.
    for m in listContent:
        getdowns(modelUrl='http://www.mzitu.com/%s'%m,picpath=picpath)
    '''
    endtime=datetime.now()
    print ("恭喜,所有美女圖片已經下載完成,下載美女照片所花費時間爲:%s秒."%(endtime-starttime).seconds)


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