5.6 WebDriver API实例讲解(41-50)

41.操作Web页面的滚动条

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

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

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

package apiSample;

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;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestDemo {
    public WebDriver driver;
    public String baseUrl;
    
    @BeforeMethod
    public void beforeMethod(){
        baseUrl="http://v.sogou.com";
        System.setProperty("webdriver.gecko.driver", "MyDriver/geckodriver.exe");
        driver =new FirefoxDriver();
        driver.get(baseUrl);
    }
    //priority=1表示测试用例以第一优先级运行
    @Test(priority=1)
    public void scrollingToBottomofAPage()
    {
        //使用JavaScript的scrollTo函数和document.body.scrollHeight参数将页面的滚动条滑动到页面的最下方
        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,document.body.scrollHeight)");
        //停顿3秒,用于人工验证滚动条是否滑动到指定的位置。根据测试需要,可注释下面的停顿代码
        try{
            Thread.sleep(3000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }
    @Test(priority=2)
    public void scrollingToElementofAPage(){
        WebElement element=driver.findElement(By.partialLinkText("综艺节目"));
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element);
        try{
            Thread.sleep(5000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }
    @Test(priority=3)
    public void scrollingByCoordinatesofAPage(){
        ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,800)");
        try{
            Thread.sleep(3000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }
    
    @AfterMethod
    public void afterMethod(){
        driver.quit();
    }
}

猜你喜欢

转载自www.cnblogs.com/yytesting/p/9080279.html