我有一个 Python 脚本,它使用 Selenium 来做一些网页点击和抓取。脚本在 Ubuntu 上运行,在 EC2 实例上运行。基本代码:
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import datetime
from datetime import datetime as dt
import re
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import ElementNotVisibleException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
#Set driver options
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--window-size=1420,1080')
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-gpu')
options.add_argument("--disable-notifications")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(chrome_options=options, executable_path=r'/Applications/chromedriver_91')
# Do a bunch of stuff................
driver.quit() #invoke after web-scraping
是否 driver.quit()
,在这种情况下,基本上与 Linux 命令 pkill chrome
执行相同的操作?有时,这个脚本会因为内存不足而崩溃。使用 pkill chrome
结合 pkill -f "(chrome)?(--headless)"
在终端本身通常会杀死所有进程并释放内存,然后脚本将运行。是
driver.quit()
足以以 headless 或其他方式关闭所有 Chrome 进程?在我的 Python 脚本中添加一些内容,例如:import os
os.system("pkill chrome")
做任何 driver.quit()
是不是已经在做?我只是想通过确保在 Python 脚本运行后完全关闭 Chrome 来最大程度地减少崩溃的可能性。
最佳答案
driver.quit()
仅退出(关闭)这个具体driver
目的。
这肯定会不是 关闭任何其他正在运行的driver
过程。
chromedriver 涉及的进程也显示为 chromedriver
或 chromedriver (32 bit)
,而不是 chrome
. chrome
process 是您的 Chrome 浏览器,而不是 Selenium 网络驱动程序。
为确保关闭 chromedriver,您可以使用 try-except-finally
涉及driver.quit()
里面finally
堵塞。
我不确定这是最佳方法,因为 AFAIK 这可能会影响报告机制。
关于python - driver.quit() 和 pkill chrome 释放内存的效果一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68491693/