Selenium:如何找到 add_arguments() 的正确命令?

问题描述

我正在使用 selenium python 和 chrome 驱动程序,想知道是否有任何方法可以获得在 add_arguments() 函数中启用或禁用选项的命令。例如,有'--disable-infobars'等,但是如果我遇到一个新的设置,我如何找到它合适的命令? 一个例子是自动下载 pdf 的设置。 任何帮助表示赞赏。

解决方法

Chromium 有很多命令开关,例如 --disable-extensions--disable-popup-blocking,可以在运行时使用 Options().add_argument()

这是一些 Chromium Command Line Switches 的列表。

Chromium 还允许其他运行时启用的功能,例如 useAutomationExtensionplugins.always_open_pdf_externally. 这些功能是使用 DesiredCapabilities. 启用的

当我需要找到其他要使用 DesiredCapabilities. 控制的功能时,我通常会查看 Chromium 的 source code

下面的代码使用命令开关和运行时启用的功能,在没有提示的情况下自动将 PDF 文件保存到磁盘。

我从国会图书馆下载了一个 PDF 文件作为回答。

如果您对此代码有任何疑问或与您的问题相关的其他问题,请告诉我。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

chrome_options = Options()
chrome_options.add_argument('--disable-infobars')
chrome_options.add_argument('--start-maximized')
chrome_options.add_argument('--disable-extensions')
chrome_options.add_argument('--disable-popup-blocking')

# disable the banner "Chrome is being controlled by automated test software"
chrome_options.add_experimental_option("useAutomationExtension",False)
chrome_options.add_experimental_option("excludeSwitches",['enable-automation'])


# you can set the path for your download_directory
prefs = {
    'download.default_directory': 'download_directory','download.prompt_for_download': False,'plugins.always_open_pdf_externally': True
}

capabilities = DesiredCapabilities().CHROME
chrome_options.add_experimental_option('prefs',prefs)
capabilities.update(chrome_options.to_capabilities())

driver = webdriver.Chrome('/usr/local/bin/chromedriver',options=chrome_options)

url_main = 'https://www.loc.gov/aba/publications/FreeLCC/freelcc.html'

driver.get(url_main)

driver.implicitly_wait(20)

download_pdf_file = driver.find_element_by_xpath('//*[@id="main_body"]/ul[2]/li[1]/a')
download_pdf_file.click()
,

您可以通过以下方式使用 Python 向 Chrome 网络驱动程序添加选项参数:

    options = webdriver.ChromeOptions()

    # Arguments go below
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-gpu")
    options.add_argument("--window-size=800,600")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--user-agent={}".format("your user agent string"))
    # Etc etc..

    options.binary_location = "absolute/path/to/chrome.exe"
    driver = webdriver.Chrome(
        desired_capabilities=caps,executable_path="absolute/path/to/chromium-driver.exe",options=options,)

Here you can find the list of all the supported arguments 用于 chrome。