我目前使用硒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
其他回答
方法如下图所示:
在python中,你可以使用
driver.execute_script("window.scrollTo(0, Y)")
(Y为要滚动到的垂直位置)
这段代码滚动到底部,但不需要每次都等待。它会不断滚动,然后在底部停止(或超时)
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get('https://example.com')
pre_scroll_height = driver.execute_script('return document.body.scrollHeight;')
run_time, max_run_time = 0, 1
while True:
iteration_start = time.time()
# Scroll webpage, the 100 allows for a more 'aggressive' scroll
driver.execute_script('window.scrollTo(0, 100*document.body.scrollHeight);')
post_scroll_height = driver.execute_script('return document.body.scrollHeight;')
scrolled = post_scroll_height != pre_scroll_height
timed_out = run_time >= max_run_time
if scrolled:
run_time = 0
pre_scroll_height = post_scroll_height
elif not scrolled and not timed_out:
run_time += time.time() - iteration_start
elif not scrolled and timed_out:
break
# closing the driver is optional
driver.close()
这比每次等待0.5-3秒的响应要快得多,因为每次响应可能需要0.1秒
ScrollTo()函数不再工作。这是我用过的,效果很好。
driver.execute_script("document.getElementById('mydiv').scrollIntoView();")
下面是一个示例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
driver.execute_script("document.getElementById('your ID Element').scrollIntoView();")
这对我的案子起作用了。
推荐文章
- 在Python中创建一个初始容量的列表
- Pylint在Visual Studio代码中“未解决的导入”错误
- Matplotlib错误-没有名为tkinter的模块
- 0到1之间的随机数?
- 使用Boto3将S3对象作为字符串打开
- "pip install——editable ./" vs "python setup.py develop"
- Pandas:索引数据帧时的多个条件-意外行为
- 如何更改Django应用程序的名称?
- 如何在python抽象类中创建抽象属性?
- “克隆”行或列向量
- 在python shell中按方向键时看到转义字符
- Cypress:只运行一个测试
- 在pip install中方括号是什么意思?
- 使用Matplotlib以非阻塞的方式绘图
- 使用sklearn缩放Pandas数据框架列