如何在Selenium Python中降低Chromedriver的CPU使用率?

3
我正在尝试使用Python中的Selenium自动化登录和抓取数据,使用Chromedriver作为驱动程序。但我想要使用5个账户进行操作,目前还在探索什么是最好的方法。
目前,我在Python文件中编写了代码,然后创建了批处理文件来运行Python。这样我就可以打开多个批处理文件,使用多个账户进行操作。
但问题在于CPU使用率过高,所以我只能使用3个账户进行操作。
到目前为止,我做的故障排除工作是使用以下代码更改选项,使Chrome无头运行:
    self.options = webdriver.ChromeOptions()
    self.options.headless = True
    self.options.add_argument(f'user-agent={user_agent}')
    self.options.add_argument("--window-size=1920,1080")
    self.options.add_argument('--ignore-certificate-errors')
    self.options.add_argument('--allow-running-insecure-content')
    self.options.add_argument("--disable-extensions")
    self.options.add_argument("--proxy-server='direct://'")
    self.options.add_argument("--proxy-bypass-list=*")
    self.options.add_argument("--start-maximized")
    self.options.add_argument('--disable-gpu')
    self.options.add_argument('--disable-dev-shm-usage')
    self.options.add_argument("--FontRenderHinting[none]")
    self.options.add_argument('--no-sandbox')
    self.options.add_argument('log-level=3')
    self.driver = webdriver.Chrome(executable_path="chromedriver.exe", options=self.options)

但我仍然无法达成我的目标(5个账户),有什么方法可以帮助我实现目标吗?

谢谢。

2个回答

2

我通过观察测试运行时的htop进程,发现Chrome的崩溃报告占用了大量的CPU和内存。

由于您正在使用Chrome Headless,我发现添加以下内容可以将CPU使用率减少约20%:

--disable-crash-reporter

这将仅在您运行Headless时禁用崩溃报告。这可能会加快速度!

我的当前设置如下,我将CPU降低了(但仅节省了一点时间),降低了约20%:

    self.options.add_argument("--no-sandbox");
    self.options.add_argument("--disable-dev-shm-usage");
    self.options.add_argument("--disable-renderer-backgrounding");
    self.options.add_argument("--disable-background-timer-throttling");
    self.options.add_argument("--disable-backgrounding-occluded-windows");
    self.options.add_argument("--disable-client-side-phishing-detection");
    self.options.add_argument("--disable-crash-reporter");
    self.options.add_argument("--disable-oopr-debug-crash-dump");
    self.options.add_argument("--no-crash-upload");
    self.options.add_argument("--disable-gpu");
    self.options.add_argument("--disable-extensions");
    self.options.add_argument("--disable-low-res-tiling");
    self.options.add_argument("--log-level=3");
    self.options.add_argument("--silent");

我发现这是一个相当不错的列表(我认为是完整的),其中附带了命令行开关的解释:https://peter.sh/experiments/chromium-command-line-switches/
此外,还提到了一些其他可以关闭的内容:https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md
我希望这对某人有帮助。

-1
self.options.add_argument('--headless')

这将使驱动程序运行比以前更快


OP的代码第2行已经设置了Headless。 - muad-dweeb
没有,它没有被指定正确的方式。 - huzefausama

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接