WebDriver应用实例(java)——操作web页面的滚动条

        目的:

        (1)、滑动页面的滚动条到页面的最下面。

        (2)、滑动页面的滚动条到页面的某个元素。

        (3)、滑动页面的滚动条向下移动某个数量的像素。

        被测试网页:http://v.sogou.com

        实例代码:

package cn.om.webdriverapi;


import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;

public class TestScrolling {

	WebDriver driver;
	String url;

	// 滑动页面的滚动条到页面的最下方
	@Test(priority = 1)
	public void scrollingToBottomofAPage() {
		// 使用JavaScript的scrollTo方法和document.body.scrollHeight参数,将页面的滚动条华东到页面的最下方
		((JavascriptExecutor) driver).executeScript("window.scrollTo(0,document.body.scrollHeight)");
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test(priority = 2)
	public void scrollingToElementofAPage() {
		// 查找到“电视剧”标签的所在位置
		WebElement element = driver.findElement(By.xpath(".//*[@id='container']/div[2]/div[2]/div[2]/div[1]/h3/a"));
		// 使用JavaScript的scrollIntoView()方法将滚动条滚动到页面的指定元素位置
		((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element);
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 滑动页面的滚动条向下移动某个数量的像素
	@Test(priority = 3)
	public void scrollingByCoordinatesofAPage() {
		// 使用JavaScript中的scrollBy方法,使用0,,800作为横纵坐标参数。
		// 将页面的滚动条纵向下滑800个像素
		((JavascriptExecutor) driver).executeScript("window.scrollBy(0,800)");
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@BeforeMethod
	public void beforeMethod() {
		url = "http://v.sogou.com";
		System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe");
		driver = new FirefoxDriver();
		driver.get(url);
	}

	@AfterMethod
	public void afterMethod() {
		driver.quit();
	}

}

猜你喜欢

转载自blog.csdn.net/vikeyyyy/article/details/80183403