Selenium python无法向下滚动

时间:2016-02-09 11:08:34

标签: python python-2.7 selenium selenium-webdriver

尝试使用selenium-webdriver python向下滚动到页面底部,以便加载更多产品。

driver = webdriver.Firefox()
driver.get('https://www.woolworths.com.au/Shop/Browse/back-to-school/free-school-labels')
driver.implicitly_wait(100)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(100)
driver.quit()

网页加载但不会更改。

我错过了什么吗?

3 个答案:

答案 0 :(得分:2)

您可以尝试使用Action Chains

element = driver.find_element_by_id("id") # the element you want to scroll to 
ActionChains(driver).move_to_element(element).perform()

答案 1 :(得分:2)

我只是尝试了这种方法,它对我有用:

element = driver.find_element_by_xpath("//div[@class='center-content']")
driver.execute_script("return arguments[0].scrollIntoView(0, document.documentElement.scrollHeight-10);", element)

首先,选择要向下滚动的页面的div元素,然后向下滚动该元素中的

OBS:我在定义scrollHeight时添加了一个偏移量,因为如果滚动到绝对底部,它不会加载更多对象。当你靠近底部而不到达目录时,它会开始加载目录。

document.documentElement.scrollHeight-10

答案 2 :(得分:2)

你可以试试这些move_up和move_down函数:

driver.maximize_window()
driver.get('https://www.woolworths.com.au/Shop/Browse/back-to-school/free-school-labels')
driver.implicitly_wait(15)
centerPanel = driver.find_element_by_css_selector("#center-panel > div[class*='hideScroll-wrapper']")
jsScript = """
        function move_up(element) {
            element.scrollTop = element.scrollTop - 1000;
        }

        function move_down(element) {
            element.scrollTop = element.scrollTop + 1000;
        }

        move_down(arguments[0]);
        move_down(arguments[0]);
        """
driver.execute_script(jsScript, centerPanel)

time.sleep(3) 

jsScript = """
        function move_up(element) {
            element.scrollTop = element.scrollTop - 1000;
        }

        function move_down(element) {
            console.log('Position before: ' + element.scrollTop);
            element.scrollTop = element.scrollTop + 1000;
            console.log('Position after: ' + element.scrollTop);
        }

        move_up(arguments[0]);
        """
driver.execute_script(jsScript, centerPanel)