我目前使用硒webdriver解析通过facebook用户的朋友页面,并从AJAX脚本提取所有id。但我需要向下滚动来找到所有的朋友。如何向下滚动硒。我正在使用python。
当前回答
这是你如何向下滚动网页:
driver.execute_script("window.scrollTo(0, 1000);")
其他回答
element=find_element_by_xpath("xpath of the li you are trying to access")
element.location_once_scrolled_into_view
当我试图进入一个不可见的“li”时,这很有帮助。
使用“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上的例子……
你可以使用
driver.execute_script("window.scrollTo(0, Y)")
其中Y是高度(在全高清显示器上是1080)。(感谢@lukeis)
你也可以使用
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
滚动到页面底部。
如果你想滚动到一个无限加载的页面,比如社交网络,facebook等(感谢@Cuong Tran)
SCROLL_PAUSE_TIME = 0.5
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
另一种方法(感谢Juanse)是,选择一个对象和
label.sendKeys(Keys.PAGE_DOWN);
出于我的目的,我想要更多地向下滚动,记住窗口的位置。我的解决方案类似,使用window.scrollY
driver.execute_script("window.scrollTo(0, window.scrollY + 200)")
哪个会到当前的y轴滚动位置+ 200
推荐文章
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试