您好,登錄后才能下訂單哦!
import requests
from lxml import etree
import re
import time
from multiprocessing import Pool #導入multiprocessing庫的Pool模塊
headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'}
def get_info(url):
html = requests.get(url,headers = headers)
selector = etree.HTML(html.text)
names = selector.xpath('//*[@class="article block untagged mb15 typs_hot"]/div[1]/a[2]/h3/text()')
centents = re.findall('<div class="content">.*?<span>(.*?)</span>',html.text,re.S) #第一個正則是為了匹配換行符
laughs = re.findall('<span class="stats-vote"><i class="number">(\d+)</i>',html.text,re.S)
comments = re.findall('<i class="number">(\d+)</i> 評論',html.text,re.S)
for name,centent,laugh,comment in zip(names,centents,laughs,comments):
info = {
'name':name,
'centent':centents,
'laugh':laughs,
'comment':comments
}
return (info)
if __name__ == '__main__':
urls = ["https://www.qiushibaike.com/text/page/{}/".format(num)for num in range(0,14)]
start_1 = time.time()
for url in urls:
get_info(url)
end_1 = time.time()
print('串行爬取花費時間:' + str(end_1 - start_1))
start_2 = time.time()
pool = Pool(processes=2) #創建進程池,processes為設置的進程個數
pool.map(get_info,urls) #利用map()函數運行進程,參數fuc為運行的函數,iterable為迭代參數
end_2 = time.time()
print('2個進程:' + str(end_2 - start_2))
start_3 = time.time()
pool = Pool(processes=4) # 創建進程池,processes為設置的進程個數
pool.map(get_info, urls) # 利用map()函數運行進程,參數fuc為運行的函數,iterable為迭代參數
end_3 = time.time()
print('4個進程:' + str(end_3 - start_3))
輸出:
D:\Python\venv\Scripts\python.exe D:/Python/venv/test12.py
串行爬取花費時間:5.043288469314575
2個進程:3.351191759109497
4個進程:2.882164716720581
Process finished with exit code 0
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。