如何在Selenium WebDriver Java中使用JavaScript

Rip*_*sim 44 javascript java selenium-webdriver

我想使用Java与WebDriver(Selenium 2)一起使用JavaScript.

我已经按照一些指南和" 入门"页面进行操作:第一行有一条指令可以运行:

$ ./go webdriverjs
Run Code Online (Sandbox Code Playgroud)

我的问题:从哪个文件夹/位置运行/执行上面提到的命令?

Pet*_*ček 117

根据您之前的问题,我想您想要从Java运行JavaScript代码段WebDriver.如果我错了,请纠正我.

WebDriverJs实际上是"公正"另一WebDriver语言绑定(您可以用Java编写,C#,红宝石,Python和JS甚至可能更多的语言,截至目前你的测试).特别是这一个是JavaScript,因此允许您用JavaScript编写测试.

如果要在Java中运行JavaScript代码WebDriver,请执行以下操作:

WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
    ((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
    throw new IllegalStateException("This driver does not support JavaScript!");
}
Run Code Online (Sandbox Code Playgroud)

我也喜欢这样做:

WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
    js = (JavascriptExecutor)driver;
} // else throw...

// later on...
js.executeScript("return document.getElementById('someId');");
Run Code Online (Sandbox Code Playgroud)

您可以在此处,文档中找到更多相关文档,或者最好在JavaDocs中找到JavascriptExecutor.

executeScript()需要函数调用和原材料JS了.你可以return从它得到一个值,你可以传递许多复杂的参数,一些随机的例子:

  1. // returns the right WebElement
    // it's the same as driver.findElement(By.id("someId"))
    js.executeScript("return document.getElementById('someId');");
    
    Run Code Online (Sandbox Code Playgroud)
  2. // draws a border around WebElement
    WebElement element = driver.findElement(By.anything("tada"));
    js.executeScript("arguments[0].style.border='3px solid red'", element);
    
    Run Code Online (Sandbox Code Playgroud)
  3. // changes all input elements on the page to radio buttons
    js.executeScript(
            "var inputs = document.getElementsByTagName('input');" +
            "for(var i = 0; i < inputs.length; i++) { " +
            "    inputs[i].type = 'radio';" +
            "}" );
    
    Run Code Online (Sandbox Code Playgroud)

  • @RiponAlWasim如果该函数嵌入到您的页面中,只需执行`js.executeScript("showAlert()");`.如果不是,请执行`js.executeScript("function showAlert(){alert('success');}; showAlert()");` (5认同)
  • 不错.再次谢谢.它运作良好,我得到了确切的解决方案 (3认同)
  • 非常感谢.js.executeScript("function showAlert(){alert('success');}; showAlert()"); 工作得很好.或者,我想在我的Java代码中单独编写JS代码/函数,并希望将JS函数调用为js.executeScript("showAlert()"); 在Java代码中单独编写JS代码/函数的方式/语法是什么? (2认同)

Yas*_*ash 5

带有 Selenium WebDriver 的 JavaScript

Selenium 是最受欢迎的自动化测试套件之一。Selenium 旨在支持和鼓励基于 Web 的应用程序以及各种浏览器和平台的功能方面的自动化测试。

    public static WebDriver driver;
    public static void main(String[] args) {
        driver = new FirefoxDriver(); // This opens a window    
        String url = "----";


        /*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
        driver.findElement(By.name("j_password")).sendKeys("yashwanth@123");*/

        JavascriptExecutor jse = (JavascriptExecutor) driver;       
        if (jse instanceof WebDriver) {
            //Launching the browser application
            jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[@name='j_password']")).sendKeys("admin");


//Opend Site and click on some links. then you can apply go(-1)--> back  forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();            
jse.executeScript("window.history.go(0)");
            jse.executeScript("window.history.go(-2)");
            jse.executeScript("window.history.forward(-2)");

            String title = (String)jse.executeScript("return document.title");
            System.out.println(" Title Of site : "+title);

            String domain = (String)jse.executeScript("return document.domain");
            System.out.println("Web Site Domain-Name : "+domain);

            // To get all NodeList[1052] document.querySelectorAll('*');  or document.all
            jse.executeAsyncScript("document.getElementsByTagName('*')");

            String error=(String) jse.executeScript("return window.jsErrors");
            System.out.println("Windowerrors  :   "+error);



            System.out.println("To Find the input tag position from top"); 
            ArrayList<?> al =  (ArrayList<?>) jse.executeScript(
                    "var source = [];"+
                    "var inputs = document.getElementsByTagName('input');"+
                    "for(var i = 0; i < inputs.length; i++) { " +
                       "   source[i] = inputs[i].offsetParent.offsetTop" +      //"    inputs[i].type = 'radio';"
                    "}"+
                    "return source"                 
                    );//inputs[i].offsetParent.offsetTop     inputs[i].type

            System.out.println("next");
            System.out.println("array : "+al);

            // (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys 
            Keys k = null;
            String selectAll = Keys.chord(Keys.CONTROL, "a");
            WebElement body = driver.findElement(By.tagName("body"));
            body.sendKeys(selectAll);

            // Search for text in Site. Gets all ViewSource content and checks their.
            if (driver.getPageSource().contains("login")) {
                System.out.println("Text present in Web Site");
            }

        Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
        System.out.println("Client Body Height : "+clent_height);

        // using selenium we con only execute script but not JS-functions.

    }
    driver.quit(); // to close browser
}
Run Code Online (Sandbox Code Playgroud)

要执行用户功能,将 JS 写入文件并读取为字符串并执行它以方便使用。

Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
        String js_TxtFile = ""; 
            while (sc.hasNext()) {          
                String[] s = sc.next().split("\r\n");   
                for (int i = 0; i < s.length; i++) {
                    js_TxtFile += s[i];
                    js_TxtFile += " ";
                }           
            }
        String title =  (String) jse.executeScript(js_TxtFile);
        System.out.println("Title  : "+title);
Run Code Online (Sandbox Code Playgroud)

document.title & document.getElementById() 是浏览器中可用的属性/方法。

文件.txt

var title = getTitle();
return title;

function getTitle() {
    return document.title;
}
Run Code Online (Sandbox Code Playgroud)