简体   繁体   中英

Handling headless mode in different browsers using Selenium Python client

I am currently working on a python (3.7) CLI program that uses Selenium and will be used by a diverse group of people.

The problem I ran into was the following:

For setting options like "headless" in Chrome I use

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path,options=chrome_options)

For Firefox , the code looks like this:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(executable_path,options=options)

So I wanted to know if there is a way to normalise these settings/ handle different browsers elegantly or do I have to write everything basically 2 or even 3 (might add Safari or Opera) times?

As per the Change Log of Selenium Python client v3.12.0 :

  • Deprecate Options set_headless methods in favor of property setter

Hence, if you are using Selenium WebDriver v 3.12.0 or above, instead of chrome_options.add_argument("--headless") you need to use the headless property setter as follows:

options.headless = True

Else you may see a DeprecationWarning as follows:

DeprecationWarning: use setter for headless property instead of set_headless opts.set_headless(headless=True)

You can find a relevant detailed discussion in DeprecationWarning: use setter for headless property instead of set_headless opts.set_headless(headless=True) using Geckodriver and Selenium in Python


References

A couple of relevant discussions:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM