首先我們需要匯入以下模組
為了防止王者榮耀的網頁後台識別出爬蟲,我們需要偽裝成瀏覽器,這裡我們需要在chrome的network中找到import requests
from urllib import request
from urllib import parse
import queue
import threading
import os
import time
headers
和referer
這兩項
在這個專案中我使用的是headers=
queue
安全佇列,利用生產者和消費者模式,我定義了兩個類,並繼承threading.thread
生產者:getinfo
消費者:s**einfoclass
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(
("%s執行緒執行完成"
%threading.current_thread(
).name)
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...