繁体   English   中英

如何在 Selenium WebDriver Java 中使用 JavaScript

[英]How to use JavaScript with Selenium WebDriver Java

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

我遵循了一些指南和入门页面:第一行有一条指令可以作为:

$ ./go webdriverjs

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

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

WebDriverJs实际上“只是”另一种WebDriver语言绑定(您可以使用 Java、C#、Ruby、Python、JS 以及目前可能的更多语言编写测试)。 这尤其是 JavaScript,因此允许您使用 JavaScript 编写测试。

如果您想在 Java WebDriver运行 JavaScript 代码,请改为执行以下操作:

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

我也喜欢这样做:

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

// later on...
js.executeScript("return document.getElementById('someId');");

您可以在此处、文档或最好JavascriptExecutor的 JavaDocs 中找到更多相关文档。

executeScript()接受函数调用和原始 JS。 你可以从它return一个值,你可以向它传递许多复杂的参数,一些随机的例子:

1.

    // returns the right WebElement
    // it's the same as driver.findElement(By.id("someId"))
    js.executeScript("return document.getElementById('someId');");
  1.  // draws a border around WebElement WebElement element = driver.findElement(By.anything("tada")); js.executeScript("arguments[0].style.border='3px solid red'", element);
  2.  // 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';" + "}" );

带有 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
}

要执行用户功能,将 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);

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

文件.txt

var title = getTitle();
return title;

function getTitle() {
    return document.title;
}

您也可以尝试通过 JavaScript 单击:

WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);

你也可以使用jquery。 在最坏的情况下,对于顽固的页面,可能需要通过自定义 EXE 应用程序进行点击。 但首先尝试明显的解决方案。

方法调用里怎么加参数没看到,找了好久才找到,所以加在这里。 如何将参数传入(到javascript函数),使用“arguments[0]”作为参数位置,然后将参数设置为executeScript函数中的输入参数。

    driver.executeScript("function(arguments[0]);","parameter to send in");

如果您想使用 javascript 执行器读取任何元素的文本,您可以执行以下代码:

WebElement ele = driver.findElement(By.xpath("//div[@class='infaCompositeViewTitle']"));
String assets = (String) js.executeScript("return arguments[0].getElementsByTagName('span')[1].textContent;", ele);

在这个例子中,我有以下 HTML 片段,我正在阅读“156”。

<div class="infaCompositeViewTitle">
   <span>All Assets</span>
   <span>156</span>
</div>

以下代码对我有用:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;

public class SomeClass {

    @Autowired
    private WebDriver driver;

     public void LogInSuperAdmin() {
        ((JavascriptExecutor) driver).executeScript("console.log('Test test');");
     }
}

我遇到了类似的情况,并像这样解决了它:

WebElement webElement = driver.findElement(By.xpath(""));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);

您需要在 Selenium SVN 存储库检出的顶级目录中运行此命令。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM