理想情况下,使用和不使用不应该对渲染DOM 树firefox_options.headless = True
中的元素有任何重大影响,但就视口而言可能有显着差异。
例如,当 GeckoDriver/Firefox 与--headless
选项一起初始化时,默认视口是width = 1366px, height = 768px
当 GeckoDriver/Firefox 在没有--headless
选项的情况下初始化时,默认视口是width = 1382px, height = 744px
.
示例代码:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.FirefoxOptions()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("https://www.google.com/")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "q")))
print ("Headless Firefox Initialized")
size = driver.get_window_size()
print("Window size: width = {}px, height = {}px".format(size["width"], size["height"]))
driver.quit()
driver = webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("https://www.google.com/")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "q")))
print ("Firefox Initialized")
size = driver.get_window_size()
print("Window size: width = {}px, height = {}px".format(size["width"], size["height"]))
driver.quit()
控制台输出:
Headless Firefox Initialized
Window size: width = 1366px, height = 768px
Firefox Initialized
Window size: width = 1382px, height = 744px
结论
从上面的观察可以推断,使用--headless
选项 GeckoDriver/Firefox 打开带有减少视口的浏览上下文,因此识别的元素数量可以更少。
解决方案
使用 GeckoDriver/Firefox 启动浏览上下文时,始终在maximized
模式下打开或配置set_window_size()
如下:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.FirefoxOptions()
options.headless = True
#options.add_argument("start-maximized")
options.add_argument("window-size=1400,600")
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("https://www.google.com/")
driver.set_window_size(1920, 1080)
tl; 博士
您可以在以下位置找到一些关于窗口大小的相关讨论: