我一直在玩Selenium + Chromedriver,我注意到如果启用或禁用无头,我会得到不同的结果。经过一番调查后,我发现“无头”不包括Accept-Language
标题。
无论如何都要在标题中手动添加它吗?
答案 0 :(得分:1)
Google Chrome的功能。一种方法是使用代理并为您修改标头。或者您可以使用Firefox驱动程序,因为在使用无头选项时该驱动程序不会发送不同的标题。
答案 1 :(得分:0)
理想情况下,使用和不使用--headless
选项不会对DOM Tree中要渲染的元素产生任何重大影响,但在Viewport上可能会有重大不同很担心。
例如,当ChromeDriver / Chrome与 --headless
选项一起初始化时,默认的视口为
width = 800px, height = 600px
与不使用--headless
选项初始化ChromeDriver / Chrome一样,默认视口为:
width = 1050px, height = 708px
示例代码(基于Python ):
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("https://www.google.com/")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "q")))
print ("Headless Chrome Initialized")
size = driver.get_window_size()
print("Window size: width = {}px, height = {}px".format(size["width"], size["height"]))
driver.quit()
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("https://www.google.com/")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "q")))
print ("Chrome Initialized")
size = driver.get_window_size()
print("Window size: width = {}px, height = {}px".format(size["width"], size["height"]))
控制台输出:
Headless Chrome Initialized
Window size: width = 800px, height = 600px
Chrome Initialized
Window size: width = 1050px, height = 708px
因此可以得出结论,使用--headless
选项,ChromeDriver / Chrome会使用缩小的视口打开会话,因此所标识的元素数量较少。
在使用ChromeDriver / Chrome初始化浏览实例时,始终以 maximized
模式打开:
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.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument("--headless")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("https://www.google.com/")