【问题标题】:Selenium: retrieve data that loads while scrolling downSelenium:检索向下滚动时加载的数据
【发布时间】:2013-01-29 13:02:03
【问题描述】:

我正在尝试检索页面中的元素,该页面具有 ajax-load 向下滚动功能 alla Twitter。由于某种原因,这无法正常工作。我添加了一些打印语句来调试它,我总是得到相同数量的项目,然后函数返回。我在这里做错了什么?

wd = webdriver.Firefox()
wd.implicitly_wait(3)

def get_items(items):
    print len(items)
    wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # len(items) and len(wd.find_elements-by...()) both always seem to return the same number
    # if I were to start the loop with while True: it would work, but of course... never end
    while len(wd.find_elements_by_class_name('stream-item')) > len(items):
        items = wd.find_elements_by_class_name('stream-item')
        print items
        wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    return items

def test():
    get_page('http://twitter.com/')
    get_items(wd.find_elements_by_class_name('stream-item'))

【问题讨论】:

  • 不能正常工作是什么意思?有什么错误信息吗?
  • 不,它根本没有找到在我执行向下滚动时加载的数据,因此 while 循环中的条件始终为 false

标签: python ajax testing selenium integration-testing


【解决方案1】:

试着在两者之间睡一会

wd = webdriver.Firefox()
wd.implicitly_wait(3)

def get_items(items):
    print len(items)
    wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # len(items) and len(wd.find_elements-by...()) both always seem to return the same number
    # if I were to start the loop with while True: it would work, but of course... never end

    sleep(5) #seconds
    while len(wd.find_elements_by_class_name('stream-item')) > len(items):
        items = wd.find_elements_by_class_name('stream-item')
        print items
        wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    return items

def test():
    get_page('http://twitter.com/')
    get_items(wd.find_elements_by_class_name('stream-item'))

注意:硬睡眠只是为了证明它有效。请改用 waits 包来等待智能条件。

【讨论】:

  • 页面是否真的滚动到底部?您是否明显看到加载新推文?
【解决方案2】:

while 循环中的条件是我的用例的问题。这是一个无限循环。我通过使用计数器解决了这个问题:

def get_items(items):

    item_nb = [0, 1] # initializing a counter of number of items found in page

    while(item_nb[-1] > item_nb[-2]):   # exiting the loop when no more new items can be found in the page

        items = wd.find_elements_by_class_name('stream-item')
        time.sleep(5)
        browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        item_nb.append(len(items))

    return items

```

【讨论】:

    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2012-10-05
    相关资源
    最近更新 更多