首页 > 解决方案 > 如何正确使用 selenium 和并行处理

问题描述

我正在尝试使用 Selenium 和 BeautifulSoup 抓取一堆网址。因为它们有数千个,而且我需要做的处理很复杂并且使用大量 CPU,所以我需要进行多处理(而不是多线程)。

现在的问题是我为每个 URL 打开和关闭一次 Chromedriver 实例,这增加了很多开销并使过程变慢。

我想要做的是为每个子进程创建一个 chromedriver 实例,只打开一次并保持打开状态,直到子进程完成。然而,我的尝试没有成功。

我尝试在主进程中创建实例,将 URL 集划分为进程数,并将每个子进程的 url 子集和单个驱动程序作为参数发送,以便每个子进程循环通过它获得的 url。但这根本没有运行,它没有给出结果或错误。

与多处理而不是线程类似的解决方案我遇到了递归限制错误(使用 sys 更改递归限制根本没有帮助)。

我还能做些什么来加快速度?

以下是实际工作的代码的相关部分。

from bs4 import BeautifulSoup
import re
import csv
from datetime import datetime
import numpy as np
import concurrent.futures
import multiprocessing
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--window-size=1920x1080')
options.add_argument('--no-sandbox')

def runit(row):
    driver = webdriver.Chrome(chrome_options=options)
    driver.set_page_load_timeout(500)
    driver.implicitly_wait(500)
    url = row[1]
    driver.get(url)
    html_doc = driver.page_source
    driver.quit()
    soup = BeautifulSoup(html_doc, 'html.parser')

    # Some long processing code that uses the soup object and generates the result object that is returned below with what I want    

    return result, row

if __name__ == '__main__':
    multiprocessing.freeze_support()
    print(datetime.now())
    # The file below has the list of all the pages that I need to process, along with some other pieces of relevant data
    # The URL is the second field in the csv file
    with open('D:\\Users\\shina\\OneDrive\\testTiles.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        # I have 4 cores but Windows shows 8 logical processors, I have tried other numbers below 8, but 8 seems to bring the fastest results
        with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
            results = executor.map(runit, csv_reader)

        #At a later time I will code here what I will do with the results after all the processes finish.

    print(datetime.now())

标签: pythonseleniumparallel-processing

解决方案


归根结底,您需要更多的计算能力来运行这些类型的测试,即多台计算机、browerstack、saucelabs 等。此外,查看 Docker,您可以在其中使用网格实现在多个浏览器上运行测试。

https://github.com/SeleniumHQ/docker-selenium


推荐阅读