使用 selenium 向下滚动时页面不会自动加载 Python

Page won't automatically load when scrolled down with selenium Python

我正在使用 headless Chrome 和 selenium 包。当我手动访问该网站并将其向下滚动时,它会加载更多 itens,并且列表“nomes”会在如下所示的 while 循环中更新。当我使用 selenium 和带头的浏览器时,它也可以工作。为什么页面没有无头加载?也许这无关紧要,但我也将 userAgent 从 ua.random 更改为 ua['Chrome'].

import fake_useragent
import selenium

chrome_options = Options()
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument('--incognito')
chrome_options.add_argument('--headless')
chrome_options.add_argument("--window-size=1920,1080")
userAgent = ua['Chrome']
chrome_options.add_argument(f'user-agent={userAgent}')
driver = webdriver.Chrome(executable_path=chromedriver_path, options=chrome_options)
driver.get('https://www.website.com/')
nomes = driver.find_elements_by_css_selector('my.css')
iteracao = 0
        if nomes:
            while iteracao < 3:
                iteracao += 1
                nomes = driver.find_elements_by_css_selector('my.css')
                driver.execute_script("arguments[0].scrollIntoView();", nomes[-1])
                time.sleep(1)
                wait(driver, 10).until(
                    wait_for_more_than_n_elements((By.CSS_SELECTOR, 'my.css'), len(nomes)))

哪里,我从 ,

class wait_for_more_than_n_elements(object):
    def __init__(self, locator, count):
        self.locator = locator
        self.count = count

    def __call__(self, driver):
        try:
            count = len(EC._find_elements(driver, self.locator))
            return count >= self.count
        except selexcept.StaleElementReferenceException:
            return False

我前段时间遇到了同样的问题!尝试将这些添加到您的 chrome 选项中,这对我有用。

chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("disable-infobars")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-dev-shm-usage")

我想值得注意的是,我听说用户说 --no-sandbox arg 定义 first 很重要,但对我来说似乎从来都不重要。

这适用于我的网站。

loc = nomes[-1].location['y']
driver.execute_script(f"window.scrollTo(0, {loc} + 200);")
driver.execute_script(f"window.scrollTo(0, {loc} + 210);")