我的博客:acsec.xyz
微信公众号: Ac sec
一.概述
对于python爬虫,默认的是使用单线程爬虫,在批量爬数据时速度太慢。但有的人会说,python的多线程爬虫,并不是真正意义上的多线程,它会有阻塞。但是,无论怎么说,多线程或者是多进程,速度都要比原来的单线程要快很多。当你使用多线程爬虫时,电脑风扇都会呜呜的转起来。下面举例说明多线程/多进程的创建方法,以及各种方法运行代码的速度。
二.举例
1.默认情况运行代码
input
import time
def test(str):
print ("Hello ",str)
time.sleep(2)
name_list =['a','b','c','d']
start_time = time.time()
for i in range(len(name_list)):
test(name_list[i])
end_time=time.time()
print("完成时间: %s S"%(end_time-start_time))
output
Hello a
Hello b
Hello c
Hello d
完成时间: 8.028036832809448 S
进程已结束,退出代码为 0
2.多线程池的创建与使用
(1)使用ThreadPoolExecutor模块创建
input
import time
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
def test(str):
print ("Hello ",str)
time.sleep(2)
name_list =['a','b','c','d']
start_time = time.time()
executor = ThreadPoolExecutor(max_workers=10) # 线程个数
# submit()的参数:第一个为函数, 之后为该函数的传入参数,允许有多个
future_tasks = [executor.submit(test,i) for i in name_list]
wait(future_tasks, return_when=ALL_COMPLETED)
# 等待所有的线程完成,才进入后续的执行
end_time=time.time()
print("完成时间: %s S"%(end_time-start_time))
output
Hello a
Hello b
Hello c
Hello d
完成时间: 2.0162949562072754 S
进程已结束,退出代码为 0
(2)使用threading模块创建
input
import time
import threading
#定义多线程类
class MyThread(threading.Thread):
def __init__(self, func, args):
threading.Thread.__init__(self)
self.args = args
self.func = func
def run(self):
self.func(*self.args)
def test(str):
print ("Hello ",str)
time.sleep(2)
name_list =['a','b','c','d']
start_time = time.time()
#调用多线程类,实现循环
threadList = [MyThread(test, (i,)) for i in name_list]
#创建多线程,开始调用进程
for t in threadList:
t.setDaemon(True)
t.start()
#等待主进程结束,再进行调用
for i in threadList:
i.join()
end_time=time.time()
print("完成时间: %s S"%(end_time-start_time))
output
Hello a
Hello b
Hello c
Hello d
完成时间: 2.0125629901885986 S
3.多进程池的创建与使用
input
import time
from multiprocessing.dummy import Pool
def test(str):
print ("Hello ",str)
time.sleep(2)
name_list =['a','b','c','d']
start_time = time.time()
pool=Pool(10)
pool.map(test,name_list)
end_time=time.time()
print("完成时间: %s S"%(end_time-start_time))
output
Hello a
Hello b
Hello c
Hello d
完成时间: 2.036229372024536 S
三.爬虫实例(爬取某网站330张图片)
1.默认
2.使用ThreadPoolExecutor模块
3.使用multiprocessing模块
4.使用threading模块