selenium2java调用JavaScript方法封装

2019-08-27 14:37:15 浏览数 (1)

本人在学习selenium2java的时候,遇到元素存在但因为被其他元素挡住了,导致无法点击的问题,多方请教后,使用js点击解决了困扰。我又写了几个js点击元素的方法,现在分享出来,供大家参考。

代码语言:javascript复制
//通过js点击
public static void clickByJs(WebDriver driver, WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
//第二种点击方法
// ((JavascriptExecutor) driver).executeScript("arguments[0].click()", question);
}

下面这个方法在发散一下,写了一些Selenium调用JavaScript的方法封装。

代码语言:javascript复制
    //通过js点击
    public void clickByJs(WebElement element) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].click();", element);
        //第二种点击方法
//        ((JavascriptExecutor) driver).executeScript("arguments[0].click()", question);
    }
    //通过xpath获取元素用js点击
    public void clickByJsByXpath(String xpath) {
        clickByJs(driver.findElement(By.xpath(xpath)));
    }
    public void clickByJsByText(String text) {
        clickByJs(findElementByText(text));
    }
    public void clickByJsById(String id) {
        clickByJs(findElementById(id));
    }
    public void clickByJsByClassName(String name) {
        clickByJs(findElementByClassName(name));
    }
    public void clickByJsByName(String name) {
        clickByJs(findElementByName(name));
    }

        //滚动到最上方
    public void scrollToTop() {
        ((JavascriptExecutor)driver).executeScript("window.scrollTo(0,0);");
//        JavascriptExecutor js = (JavascriptExecutor) driver;
//        js.executeScript("window.scrollTo(0,0);");
    }
    //js滚动页面内div
    public void scrollToBottomById(String id) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].scrollTo(0, 3000);", findElementById(id));
    }
    //使用js使元素隐藏元素显示
    public void makeDisplayById(String id) {
        JavascriptExecutor  js = (JavascriptExecutor)driver;
        js.executeScript("document.getElementById(id).style.display='block';");
    }
    public void makeElementDisplay(WebElement element) {
        JavascriptExecutor  js = (JavascriptExecutor)driver;
//        WebElement element = driver.findElement(By.xxx);
        js.executeScript("arguments[0].style=arguments[1]", element, "display: block;");
    }
    //js输入文本
    public void inputTextByJsById(String text, String id) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].value="2016-08-20"",driver.findElement(By.id(id)));
    }
    //js输入文本
    public void inputTextByJs(String text, WebElement element) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].value="   text   """, element);
    }

0 人点赞