5.1.threading模塊 簡單使用 5.2.生產者和消費者 Lock模式的生產者和消費者 5.3.下載表情包 網址:http://www.doutula.com/photo/list/?page=1 解析:xpath 不用多線程,速度相對會很慢 利用多線程 main() 定義兩個隊列,和創建多 ...
5.1.threading模塊
簡單使用
import threading,time def coding(): for x in range(3): print('正在寫代碼%s'%x) time.sleep(2) def drawing(): for x in range(3): print('正在畫畫%s'%x) time.sleep(2) def main(): t1 = threading.Thread(target=coding) t2 = threading.Thread(target=drawing) t1.start() t2.start() if __name__ == '__main__': main()
5.2.生產者和消費者
Lock模式的生產者和消費者
import threading import random,time gMoney = 1000 gLock = threading.Lock() gTotalTimes = 10 gTimes = 0 class Producer(threading.Thread): def run(self): global gMoney global gTimes while True: money = random.randint(100,1000) gLock.acquire() #只生產10次,超過就停止,必須把鎖給釋放掉,否則產生死鎖 if gTimes >= gTotalTimes: gLock.release() break gMoney += money print('%s生產了%d元錢,剩餘%d元錢' % (threading.current_thread(), money, gMoney)) #生產一次,次數加1,總共10次 gTimes += 1 gLock.release() time.sleep(0.5) class Consumer(threading.Thread): def run(self): global gMoney while True: money = random.randint(100,1000) gLock.acquire() if gMoney >= money: gMoney -= money print('%s消費了%d元錢,剩餘%d元錢' % (threading.current_thread(), money,gMoney)) else: if gTimes >= gTotalTimes: gLock.release() break gLock.release() time.sleep(0.5) def main(): for x in range(5): t1 = Producer() t1.start() for x in range(2): t2 = Consumer() t2.start() if __name__ == '__main__': main()
5.3.下載表情包
網址:http://www.doutula.com/photo/list/?page=1
解析:xpath
不用多線程,速度相對會很慢
import requests from lxml import etree from urllib import request import os import re def parse_page(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36', 'Referer': 'https://movie.douban.com/' } response = requests.get(url,headers=headers) text = response.text html = etree.HTML(text) imgs = html.xpath("//div[@class='page-content text-center']//img[@class!='gif']") for img in imgs: # print(etree.tostring(img)) #圖片地址 img_url = img.get('data-original') #圖片名字 alt = img.get('alt') #替換掉名字裡面的特殊字元 alt = re.sub(r'[\??\.,。!!\*]','',alt) #獲取圖片的尾碼名(.gif .jpg) suffix = os.path.splitext(img_url)[1] #保存的時候完整的圖片名字 filename = alt + suffix request.urlretrieve(img_url,'C:/Users/Administrator/Desktop/images/'+filename) def main(): for x in range(1,10): url = 'http://www.doutula.com/photo/list/?page=%d'%x parse_page(url) if __name__ == '__main__': main()
利用多線程
main()
- 定義兩個隊列,和創建多線程
- page_queue():存放每一頁的url
- img_queue():存放每一頁裡面所有的表情的url
Producer()
- 從page_queue()隊列中去每一頁的url,直到隊列為空則break
- 用xpath提取出每一頁的所有圖片的url
- 把每個圖片的url和名字存放到img_queue()隊列裡面
Consumer()
- 從img_queue()隊列中取出圖片的url和名字
- 下載保存
- 直到page_queue()和img_queue()兩個隊列都為空則break
代碼
import requests from lxml import etree from urllib import request import os import re import threading from queue import Queue class Producer(threading.Thread): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36', 'Referer': 'https://movie.douban.com/' } def __init__(self, page_queue, img_queue, *args, **kwargs): super(Producer, self).__init__(*args, **kwargs) self.page_queue = page_queue self.img_queue = img_queue def run(self): while True: if self.page_queue.empty(): break url = self.page_queue.get() self.parse_page(url) def parse_page(self,url): response = requests.get(url,headers=self.headers) text = response.text html = etree.HTML(text) imgs = html.xpath("//div[@class='page-content text-center']//img[@class!='gif']") for img in imgs: # print(etree.tostring(img)) #圖片地址 img_url = img.get('data-original') #圖片名字 alt = img.get('alt') #替換掉名字裡面的特殊字元 alt = re.sub(r'[\??\.,。!!\*]','',alt) #獲取圖片的尾碼名(.gif .jpg) suffix = os.path.splitext(img_url)[1] #保存的時候完整的圖片名字 filename = alt + suffix self.img_queue.put((img_url,filename)) class Consumer(threading.Thread): def __init__(self,page_queue,img_queue,*args,**kwargs): super(Consumer, self).__init__(*args,**kwargs) self.page_queue = page_queue self.img_queue = img_queue def run(self): while True: if self.img_queue.empty() and self.page_queue.empty(): break img_url,filename = self.img_queue.get() request.urlretrieve(img_url, 'C:/Users/Administrator/Desktop/images/' + filename) print("已下載完一張圖片") def main(): page_queue = Queue(1000) img_queue = Queue(10000) for x in range(1,1758): url = 'http://www.doutula.com/photo/list/?page=%d'%x page_queue.put(url) for x in range(10): t = Producer(page_queue,img_queue) t.start() for x in range(10): t = Consumer(page_queue,img_queue) t.start() if __name__ == '__main__': main()
結果: