我目前使用硒webdriver解析通过facebook用户的朋友页面,并从AJAX脚本提取所有id。但我需要向下滚动来找到所有的朋友。如何向下滚动硒。我正在使用python。


当前回答

下面是一个示例selenium代码片段,您可以将其用于这种类型的目的。它会转到youtube搜索结果的url“Enumerate python tutorial”,然后向下滚动,直到找到标题为“Enumerate python tutorial(2020)”的视频。

driver.get('https://www.youtube.com/results?search_query=enumerate+python')
target = driver.find_element_by_link_text('Enumerate python tutorial(2020).')
target.location_once_scrolled_into_view

其他回答

insert this line driver.execute_script("window.scrollBy(0,925)", "")

你可以使用send_keys来模拟PAGE_DOWN键(通常滚动页面):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.PAGE_DOWN)

只是目前提供的解决方案的一个小变化:有时在刮痧中你必须满足以下要求:

一步一步地滚动。否则,如果你总是跳到底部,一些元素只作为容器/div加载,但它们的内容没有加载,因为它们从来都不可见(因为你直接跳到底部); 为加载内容留出足够的时间; 这不是一个无限滚动的页面,有一个终点,你必须确定什么时候到达终点;

下面是一个简单的实现:

from time import sleep
def keep_scrolling_to_the_bottom():
    while True:
        previous_scrollY = my_web_driver.execute_script( 'return window.scrollY' )
        my_web_driver.execute_script( 'window.scrollBy( 0, 230 )' )
        sleep( 0.4 )
        if previous_scrollY == my_web_driver.execute_script( 'return window.scrollY' ):
            print( 'job done, reached the bottom!' )
            break

测试和工作在Windows 7 x64, Python 3.8.0, selenium 4.1.3,谷歌Chrome 107.0.5304.107,物业租赁网站。

使用“send keys”方法滚动页面的循环:

pre_scroll_height = driver.execute_script('return document.body.scrollHeight;')
while True:
    driver.find_element_by_tag_name('body').send_keys(Keys.END)
    time.sleep(5)
    post_scroll_height = driver.execute_script('return document.body.scrollHeight;')

    print(pre_scroll_height, post_scroll_height)
    if pre_scroll_height == post_scroll_height:
        break
    pre_scroll_height=post_scroll_height

如果你想在一个特定的视图/帧(WebElement)内滚动,你只需要用你想要滚动的特定元素替换“body”。在下面的例子中,我通过“getElementById”获得该元素:

self.driver.execute_script('window.scrollTo(0, document.getElementById("page-manager").scrollHeight);')

这就是YouTube上的例子……