利用threading多執行緒爬取王者榮耀的高畫質桌布

2022-09-10 20:15:16 字數 3723 閱讀 3502

首先我們需要匯入以下模組

import requests

from urllib import request

from urllib import parse

import queue

import threading

import os

import time

為了防止王者榮耀的網頁後台識別出爬蟲,我們需要偽裝成瀏覽器,這裡我們需要在chrome的network中找到headersreferer這兩項

headers=

在這個專案中我使用的是queue安全佇列,利用生產者和消費者模式,我定義了兩個類,並繼承threading.thread

生產者:getinfo

class

getinfo

(threading.thread)

:def

__init__

(self,page_queue,image_queue,

*args,

**kwargs)

:super

(getinfo, self)

.__init__(

*args,

**kwargs)

self.page_queue = page_queue

self.image_queue = image_queue

@staticmethod

defextract_images

(data)

: images =

for x in

range(1

,9):

image_urls = parse.unquote(data[

'sprodimgno_%d'

% x]

).replace(

'200'

,'0'

)return images

defrun

(self)

->

none

:while

not self.page_queue.empty():

page_url = self.page_queue.get(

) resp = requests.get(page_url,headers=headers)

datas = resp.json(

).get(

"list"

)for data in datas:

img_urls = getinfo.extract_images(data)

name = parse.unquote(data[

'sprodname'])

.replace(

'1:1',''

).strip(

) dir_path = os.path.join(

"image"

,name)

ifnot os.path.exists(dir_path)

: os.mkdir(dir_path)

for index,img_url in

enumerate

(img_urls)

: self.image_queue.put(

)print

("%s執行緒執行完成"

%threading.current_thread(

).name)

消費者:s**einfo

continue在的儲存中,我們需要套用兩個try-except**塊,這樣即使在訪問錯誤的情況下,程式依舊會執行下去。

main函式中,我們分別對王者榮耀桌布頁碼佇列和佇列進行大小設定。

def

main()

: page_queue = queue.queue(21)

image_queue = queue.queue(

1000

)for x in

range(21

):page_url =

.format

(x) page_queue.put(page_url)

for x in

range(8

):th = getinfo(page_queue,image_queue,name=

"資料線程%d"

%x) th.start(

)for x in

range(8

):th = s**einfo(page_queue,image_queue,name=

"資料線程%d"

%x) th.start(

)if __name__ ==

"__main__"

: main(

)

多執行緒 threading

python的thread模組是 較底層的模組,python的threading 模組是對thread做了 些包裝的,可以更加 便的被使 1.執行緒執 的封裝 通過上 節,能夠看出,通過使 threading模組能完成多工的程式開 發,為了讓每個執行緒的封裝性更完美,所以使 threading模組時...

threading多執行緒

什麼是執行緒?執行緒是作業系統能夠進行運算排程的最小單位。它被包含在程序之中,是程序中的實際運作單位。一條執行緒指的是程序中乙個單一順序的控制流,乙個程序中可以併發多個執行緒,每條執行緒並行執行不同的任務。乙個程序中可以包含多個執行緒。1 import threading 2import time ...

python 多執行緒 Threading

簡單的多執行緒 python 2.7 coding utf 8 import threading defrun thread while true cmd input input you choice print cmd if cmd 0 print thread exit break else p...