【问题标题】:How can I execute a "scrollIntoView()" function if the headless of the webdriver is equals to True?如果 webdriver 的 headless 等于 True,我如何执行“scrollIntoView()”函数?
【发布时间】:2020-12-20 03:33:07
【问题描述】:

我正在尝试执行将内部 div 向下滚动到某个元素的代码。只有在以下情况下才有效:

Options().headless = False

但正如你们所知,这对整个事情的表现不利。

滚动的代码是:

element = driver1.find_element_by_xpath(reference)
driver1.execute_script("arguments[0].scrollIntoView();", element)

我怎么能做这样的事情,但无头等于 True?

【问题讨论】:

  • 应该完全一样。您是否尝试过遇到任何问题?
  • 是的,我尝试用这两种情况运行代码,当headless等于True时,出现错误。
  • 什么是错误信息?

标签: javascript python selenium selenium-webdriver js-scrollintoview


【解决方案1】:

scrollIntoView() 必须以相同的方式工作,而不管Options().headless = TrueOptions().headless = False

但是,在使用 模式时,您需要:

  • Maximize the browsing window

    options = Options()
    options.add_argument("--headless")
    options.add_argument("window-size=1400,600")
    
  • 另外诱导WebDriverWaitvisibility_of_element_located()如下:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "reference")))
    driver.execute_script("arguments[0].scrollIntoView();", element)
    

参考文献

您可以在以下位置找到相关的详细讨论:

【讨论】:

  • @gusta 很高兴能为您提供帮助。 Upvote 答案如果这个/任何答案对您/对您有帮助,以造福未来的读者。
猜你喜欢
  • 2019-06-16
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多