工作中遇到一个多线程需求的爬虫问题,使用多线程多次尝试难以解决,偶尔想到线程池的问题,花了10分钟简单了解之后顺利解决问题。
threadpool模块
一、安装方式
pip install threadpool
pool = threadpool.ThreadPool([size]) # [size]表示线程池同时容纳的线程数
requests = threadpool.makeRequests(some_callable, list_of_args, callback) # some_callable表示调用函数名, list_of_args表示传递参数列表, callback表示回调函数
[pool.putRequest(req) for req in requests] # 表示将请求队列中的元素全部放进线程池统一管理
pool.wait() # 表示所有请求结束后,结束进程
二、实例
# -*- coding:utf-8 -*-
import threadpool, time
with open(r'../uoko_house_id.txt', 'r', encoding='utf-8') as f: # with open语句表示通用的打开文件的方式,此处用来获取需要爬取参数的列表
roomIdLi = f.readlines()
roomIdList =[x.replace('\n','').replace(' ','') for x in roomIdLi]
print(roomIdList)
li = [[i, item] for i, item in enumerate(roomIdList)] # enumerate()将列表中元素和其下标重新组合输出
def run(roomId):
"""对传入参数进行处理"""
print('传入参数为:', roomId)
time.sleep(1)
def main():
roomList = li # 房间信息
start_time = time.time()
print('启动时间为:', start_time)
pool = threadpool.ThreadPool(10)
requests = threadpool.makeRequests(run, roomList)
[pool.putRequest(req) for req in requests]
pool.wait()
print("共用时:", time.time()-start_time)
if __name__ == '__main__':
main()