Python Selenium:滚动不起作用

时间:2017-01-20 07:20:31

标签: python selenium

我正在尝试自动化this Instagram链接。我需要滚动并滚动并获取所有链接。我正在尝试关注但不工作。

def fetch_links_by_hashtag(hash_tag):
    url = 'https://www.instagram.com/explore/tags/marketing/'
    driver.get(url)
    driver.implicitly_wait(20)
    is_more = False

    try:
        elem_more = wait.until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Load more")))
        elem_more.click()
        is_more = True
    except Exception as ex:
        print(str(ex))

    pop = driver.find_element_by_tag_name('footer')
    #pop = driver.find_element_by_link_text('About us')
    # pop = driver.find_element_by_class_name('_4gt3b')
    if pop is not None:
        for i in range(10):
            print('Calling scrolling script')
            # It scolls till end
            driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', pop)
            sleep(4)
        html = pop.get_attribute('innerHTML')
        print(html)

2 个答案:

答案 0 :(得分:1)

Subject: Stats of 3 files

Hi All,

PFB file details

                             filename rowcount     size
/var/tmp/file1.txt                       72229  6667249
/var/tmp/file2.txt                       44299  4343903

How to scroll down to the bottom of a page ?

答案 1 :(得分:0)

除了宏杰李回答

driver.execute_script("return arguments[0].scrollIntoView();", element_obj)

另外,如果你想做一个额外的滚动:

driver.execute_script("return arguments[0].parentNode.scrollTop = "
                      "arguments[0].parentNode.scrollTop + {extra_scroll}"
                      .format(extra_scroll=extra_scroll_pixels), element_obj)

我的整个代码:

def _scroll_to_element(driver, element,
                       extra_scroll=None):
    # Scroll to element
    driver.execute_script("return arguments[0].scrollIntoView();", element)

    # Scroll parentNode with the extra pixels (If provided)
    if extra_scroll:
        driver.execute_script(
            "return arguments[0].parentNode.scrollTop = "
            "arguments[0].parentNode.scrollTop + {extra_scroll}".format(
                extra_scroll=str(extra_scroll)), element)