Selenium Firefox headless returns 不同的结果

Selenium Firefox headless returns different results

当我抓取包含使用无头选项的产品的页面时,我得到了不同的结果。
对于同样的问题,有一次我得到的结果没有排序,而另一次得到的结果排序正确。

Selenium firefox 浏览器:

firefox_options = Options()
firefox_options.headless = True
browser = webdriver.Firefox(options=firefox_options, executable_path=firefox_driver)

根据 post:
"firefox does not send different headers when using the headless option".

如何使用无头选项从抓取中获得恒定的结果?

更新:

事实证明,广告弹出窗口 window 隐藏了价格排序菜单。通过 DebanjanB 将常量 windows 大小设置为 post,问题就解决了。

感谢任何建议

理想情况下,使用和不使用 firefox_options.headless = True 应该不会对 DOM Tree getting rendered but may have a significant difference as far as the Viewport 中的元素产生任何重大影响。

例如,当 GeckoDriver/Firefox 与 --headless 选项一起初始化时,默认的 Viewportwidth = 1366px, height = 768px 当 GeckoDriver/Firefox 在没有 --headless 选项的情况下初始化时,默认的 Viewportwidth = 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 打开 浏览上下文 并减少 视口 因此识别的元素数量可以 less.


解决方案

在使用 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;博士

您在 window size 中找到了一些相关讨论:

  • : How to set window size in Selenium Chrome Python
  • : Not able to maximize Chrome Window in headless mode