调用JavaScript控制浏览器的滚动条

代码:
package com.utils;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ScrollUtil {

    private WebDriver driver;
    private WebDriverWait wait;

    @Autowired
    ScrollUtil(Browser browser) {
        this.driver = browser.getDriver();
        driver.manage().window().maximize();
        PageFactory.initElements(browser.getDriver(), this);
        this.wait = new WebDriverWait(this.driver,30);
    }

    public void scrollSpecifiedLocation(WebElement element){
        ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true)", element);
        ((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
    }

    public void highlightElement(WebElement ele){
        ((JavascriptExecutor)driver).executeScript("arguments[0].setAttribute('style', 'border: 2px solid red;');", ele);
        ((JavascriptExecutor)driver).executeScript("arguments[0].setAttribute('style', 'border: 2px dashed black');", ele);
    }

    public void other(){
        ((JavascriptExecutor)driver).executeScript("window.scrollTo(0,500);");
        ((JavascriptExecutor)driver).executeScript("alert('Hello yanzi!');");
    }
}
package com.utils;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Component;

@Component
public class Browser {

    static WebDriver driver;

    static {
        System.setProperty("webdriver.chrome.driver","D:\\SpringWeb\\src\\main\\resources\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }

    public WebDriver getDriver(){return driver;}
}
posted @ 2021-04-19 22:36  meiyouyou  阅读(95)  评论(0编辑  收藏  举报