操作Web页面滚动条

滑动页面的JS命令:

# 绝对位置
window.scrollTo(0,document.body.scrollHeight);
window.scrollTo(0,50);
# 相对位置移动
scrollBy(0,50);
# scrollIntoView(true) 表示将元素滚动到中间
# scrollIntoView(true) 表示将元素滚动到底部
document.getElementById('id').srollIntoView(true);  #有待实战演示

scrollTo和scrollBy区别(链接)

    View类的源代码如下所示,mScrollX记录的是当前View针对屏幕坐标在水平方向上的偏移量,而mScrollY则是记录的时当前View针对屏幕在竖值方向上的偏移量。

    从以下代码我们可以得知,scrollTo就是把View移动到屏幕的X和Y位置,也就是绝对位置。而scrollBy其实就是调用的scrollTo,但是参数是当前mScrollX和mScrollY加上X和Y的位置,所以ScrollBy调用的是相对于mScrollX和mScrollY的位置。我们在上面的代码中可以看到当我们手指不放移动屏幕时,就会调用scrollBy来移动一段相对的距离。而当我们手指松开后,会调用mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);来产生一段动画来移动到相应的页面,在这个过程中系统回不断调用computeScroll(),我们再使用scrollTo来把View移动到当前Scroller所在的绝对位置。

代码:
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import unittest
import traceback
from time import sleep
class TestScrollJS(unittest.TestCase):
	def setUp(self):
		self.driver=webdriver.Firefox()
	def test_scrollJS(self):
		url = "http://www.gdut.edu.cn/"
		self.driver.get(url)
		sleep(2)
		# 向下移动到绝对位置 y=50
		self.driver.execute_script("window.scrollTo(0,50);")
		self.driver.get_screenshot_as_file('scrollTo.png')
		sleep(2)
		# 向下移动到绝对位置 y=50,页面位置相对于上一次移动并没有发生变化
		self.driver.execute_script("window.scrollTo(0,50);")
		sleep(2)
		# 页面相对于上次移动后的位置向下移动50像素并截图
		self.driver.execute_script("window.scrollBy(0,50);")
		self.driver.get_screenshot_as_file('scrollBy1.png')
		sleep(2)
		# 页面相对于上次移动后的位置再次向下移动50像素并截图
		self.driver.execute_script("window.scrollBy(0,50);")
		self.driver.get_screenshot_as_file('scrollBy2.png')
		sleep(2)		
		# 将页面的滚动条滑动到页面的最下方
		self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
		self.driver.get_screenshot_as_file('scrollToBottom.png')
	def tearDown(self):
		self.driver.quit()
if __name__ == '__main__':
	unittest.main()

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值