一共需要導(dǎo)入如下的庫
from bs4 import BeautifulSoup
import requests
import time
import threading
import queue
網(wǎng)址是https://www.doutula.com/photo/list/?page=1
首先要這是request頭。
調(diào)用request.get獲取相應(yīng),
將源代碼寫入到‘1.html’
url='https://www.doutula.com/photo/list/?page=1'
headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'}
resp=requests.get(url,headers=headers)
with open('1.html','bw') as fp:
fp.write(resp.content)
使用beautiful解析html文本,設(shè)置lxml解析器。
接下來是多線程爬取動圖。
python的多線程 使用于IO繁忙型,不適用于cpu計(jì)算型。
因?yàn)閜ython的多線程是單核多線程。無法并行,只能并發(fā)。
python自帶的隊(duì)列queue具有原子性,是線程安全的。但仍需要引入鎖來控制。
引入time庫是為了計(jì)算程序運(yùn)行時(shí)間.
with open('1.html','r',encoding='utf-8') as fp:
html=fp.read()
text=BeautifulSoup(html,'lxml')
div=text.select_one('div.page-content')
imgs=div.find_all('img')
i=0
start=time.time()
#--------------------------------------------------------------------------
def go():
global Q,i
while True:
Lock.acquire()
if(Q.empty()):
Lock.release()
break
url=Q.get()
Lock.release()
resp = requests.get(url, headers=headers)
Lock.acquire()
with open('img/' + str(i) + '.jpg', 'bw') as fp:
i += 1
Lock.release()
fp.write(resp.content)
Q=queue.Queue(90)
i=0
for img in imgs:
if (img.get('data-backup')):
img_url = img['data-backup']
Q.put(img_url)
Lock=threading.RLock()
T=[]
for cnt in range(5):
t=threading.Thread(target=go)
T.append(t)
t.start()
for t in T:
t.join()
end=time.time()
print('執(zhí)行時(shí)間:',end-start,'秒')