带硒的无头镀铬,只能找到非无头滚动的方法

use*_*711 5 python selenium google-chrome headless

关于这个主题有很多东西可以找到,但无法弄清楚。我需要滚动到(不是很长)无限滚动页面的末尾。我有 2 个选项可以与 chrome non-headless 一起使用,但似乎不能无头工作。

我最喜欢的第一个,效果很好,在 SA 上找到:

driver = webdriver.Chrome('c:/cd.exe', chrome_options=chrome_options)
driver.get('http://www.website.com')

while True:
    count = len(driver.find_elements_by_xpath('//div[@itemprop="itemListElement"]'))
    print(count)
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    try:
        WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,
                                                                          "//div[@itemprop='itemListElement'][%s]" % str(count + 1))))
    except TimeoutException:
        break
Run Code Online (Sandbox Code Playgroud)

在意识到我无法在无头模式下逃脱之后的第二个黑客工作:

driver = webdriver.Chrome('c:/cd.exe', chrome_options=chrome_options)
driver.get('https://www.website.com')

while True:

    count = len(driver.find_elements_by_xpath('//div[@itemprop="itemListElement"]'))
    actions = ActionChains(driver)
    actions.send_keys(Keys.PAGE_DOWN)
    actions.perform()
    actions.send_keys(Keys.PAGE_DOWN)
    actions.perform()


    # focus_element_scroll = driver.find_elements_by_xpath('//section[@class="occasion-content"]')
    # driver.find_elements_by_xpath('//div[@itemprop="itemListElement"]')[-1].send_keys(Keys.PAGE_DOWN)
    # driver.find_elements_by_xpath('//div[@itemprop="itemListElement"]')[-1].send_keys(Keys.PAGE_DOWN)
    # self.driver.find_element_by_css_selector("ul.list-with-results").send_keys(Keys.ARROW_DOWN)
    print(count)
    # driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    try:  
        WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,
                                                                          "//div[@itemprop='itemListElement'][%s]" % str(count + 1))))
    except TimeoutException:
        break
Run Code Online (Sandbox Code Playgroud)

所以两者都在 chrome 中工作,但不在无头模式下工作,我需要将它们推送到 ubuntu vps,在那里它们需要无头,我知道 xvfb 选项,但我很高兴我可以删除它并使用原生 chrome,因为液滴没有太多的记忆。

编辑:刚刚尝试了这种方法,重点放在页脚中的一个元素上,也适用于非无头但不适用于无头:

ActionChains(driver).move_to_element(focus[0]).perform()
Run Code Online (Sandbox Code Playgroud)

有人有不同的方法吗?

编辑只是想知道是否可以在无头模式下使用 chrome 滚动!

use*_*711 8

在尝试了不同版本的 selenium、chrome 和 chromedriver 的 2 天后找到了答案,我几乎放弃并想使用 xvfb。

已经尝试在 chrome 参数中最大化窗口,但没有帮助。但这次我尝试设置手动窗口大小。那有帮助。

    chrome_options.add_argument("window-size=1920,1080")
Run Code Online (Sandbox Code Playgroud)

在这里发布,以便下一个不会像我一样长。