
1、使用注意
(1)使用池时,如果未指定进程数,则默认为CPU核心数。
(2)核心数量对应于计算机的逻辑处理器数量(任务管理器-性能),而不是核心数量(我的计算机有2个核心和4个逻辑处理器,因此这里默认使用4个进程)
(3)进程数可以是几十万,并不意味着开放进程的数量是4。只要使用池(10),就可以同时打开10个进程进行爬网。
(4)但是需要注意的是,无论多线程还是多进程,打开过多都会导致切换耗时,降低效率,所以创建过多的多线程和进程是谨慎的。
2、实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import requests
from bs4 import BeautifulSoup
from multiprocessing import Pool, current_process
def get_title(i):
print( 'start' , current_process().name)
title_list = []
url = 'https://movie.douban.com/top250?start={}&filter=' .format(i*25)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser' )
lis = soup.find( 'ol' , class_= 'grid_view' ).find_all( 'li' )
for li in lis:
title = li.find( 'span' , class_= "title" ).text
# return title
title_list.append(title)
print(title)
return (title_list) if __name__ == '__main__' :
pool = Pool()
for i in range(10):
pool.apply_async(get_title, (i, ))
pool.close()
pool.join()
print( 'finish' )
|
以上就是python进程池的使用注意,希望能对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。