gpt4 book ai didi

python - Selenium:检索向下滚动时加载的数据

转载 作者:太空狗 更新时间:2023-10-30 03:04:43 28 4
gpt4 key购买 nike

我正在尝试检索具有 ajax 加载向下滚动功能的页面中的元素 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'))

最佳答案

尝试在两者之间睡一觉

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'))

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

关于python - Selenium:检索向下滚动时加载的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14583560/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com