当使用多处理运行硒时,如何减少使用硒的执行时间
解决方案中的很多时间都花在为每个URL启动Webdriver上。您可以通过每个线程仅启动一次驱动程序来减少此时间:
(... skipped for brevity ...)threadLocal = threading.local()def get_driver(): driver = getattr(threadLocal, 'driver', None) if driver is None: chromeOptions = webdriver.ChromeOptions() chromeOptions.add_argument("--headless") driver = webdriver.Chrome(chrome_options=chromeOptions) setattr(threadLocal, 'driver', driver) return driverdef get_title(url): driver = get_driver() driver.get(url) (...)(...)在我的系统上,这将时间从1m7s减少到仅24.895s,减少了约35%。要测试自己,请下载完整脚本。
注意:
ThreadPool使用受Python GIL约束的线程。如果大多数情况下任务是受I /
O约束的,那没关系。根据您对抓取的结果进行的后处理,您可能需要使用a
multiprocessing.Pool。这将启动并行进程,这些进程作为一个整体不受GIL的约束。其余代码保持不变。



