网络编程
位置:首页>> 网络编程>> Python编程>> Selenium 滚动页面至元素可见的方法

Selenium 滚动页面至元素可见的方法

作者:落晨  发布时间:2022-06-01 14:01:05 

标签:Selenium,滚动页面,元素可见

滚动页面

在自动化操作中,如果web页面过长,而我们需要的元素并不在当前可视页面中,那么selenium就无法对其进行操作;此时,我们就需要像平时操作浏览器一样来滚动页面,使我们需要操作的对象可见!

滚动页面的方法:

window.scrollBy()

  • window.scrollBy(0,500)   向下滚动500个像素

  • window.scrollBy(0,-500) 向上滚动500个像素

  • window.scrollBy(500,0)   向右滚动500个像素

  • window.scrollBy(-500,0) 向左滚动500个像素

使用方式:

  • 在 开发者工具--Console中输入以上内容,即可实现页面滚动

  • 示例:window.scrollBy(0,500)  向下滚动500个像素

Selenium中实现滚动页面

  • driver.execute_script('window.scrollBy()')

  • driver.execute_script("arguments[0].scrollIntoView();", ele)滚动至元素ele可见

 代码示例:


from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.implicitly_wait(10)
# 设置窗口大小
driver.set_window_size(800, 700)

driver.get('http://baidu.com')

# 百度输入框输入 selelnium python 回车
driver.find_element_by_id("kw").send_keys("selenium python\n")

time.sleep(2)
# 向下滚动200个像素
driver.execute_script('window.scrollBy(0,200)')

time.sleep(2)
# 滚动至元素ele可见位置
eles = driver.find_elements_by_css_selector('#rs table tr th a')
ele = eles[0]
driver.execute_script("arguments[0].scrollIntoView();",ele)

time.sleep(2)
# 向右滚动200个像素
driver.execute_script('window.scrollBy(200,0)')

time.sleep(2)
driver.quit()

来源:https://www.cnblogs.com/wilson-5133/p/10996810.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com