1

我有一个 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()足以以无头或其他方式关闭所有 Chrome 进程?在我的 Python 脚本中添加一些内容,例如:

import os 
os.system("pkill chrome") 

做任何driver.quit()尚未做的事情?我只是想通过确保在 Python 脚本运行后完全关闭 Chrome 来最大程度地减少崩溃的可能性。

4

1 回答 1

0

driver.quit()仅退出(关闭)特定driver对象。
这绝对不会关闭任何其他正在运行的driver进程。
chromedriver 涉及的进程也显示为chromedriveror chromedriver (32 bit), not chromechromeprocess 是您的 Chrome 浏览器,而不是 Selenium 网络驱动程序。
为确保关闭 chromedriver,您可以在块内使用try-except-finally涉及。 我不确定这是最佳方法,因为 AFAIK 这可能会影响报告机制。driver.quit()finally

于 2021-07-22T22:20:17.047 回答