【问题标题】:Page won't automatically load when scrolled down with selenium Python使用 selenium Python 向下滚动时页面不会自动加载
【发布时间】:2021-08-03 01:34:39
【问题描述】:

我正在使用带有 selenium 包的无头 Chrome。当我手动访问该网站并向下滚动时,它会加载更多的 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)))

哪里,我从here得到的,

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

【问题讨论】:

    标签: python selenium scroll webdriver load


    【解决方案1】:

    不久前我遇到了同样的问题!尝试将这些添加到您的 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 很重要,但对我来说似乎并不重要。

    【讨论】:

      【解决方案2】:

      这适用于我的网站。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-05
        相关资源
        最近更新 更多