如何在selenium中执行js?

时间:2015-11-12 13:39:37

标签: javascript java selenium webdriver

Selenium WebDriver Java

任何人都知道如何执行此脚本js.executeScript("window.addEventListener('load',function(){document.getElementsByTagName('script')[1].src='google.com'})");

js.executeScript("window.load = function()
{document.getElementsByTagName('script')[1].src='google.com'})");

此脚本返回null。 Eclipse说:线程中的异常" main"显示java.lang.NullPointerException     在autotesting.itacademy.main(itacademy.java:58)

这里的主要代码是:

package autotesting;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

//for read and write from file
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;

public class itacademy {

     private static WebDriver driver = null;

     public static JavascriptExecutor js = (JavascriptExecutor) driver;

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        JavascriptExecutor js = (JavascriptExecutor) driver;

        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();        
        driver.get("http://office.co.uk/");

        js.executeScript("window.addEventListener('load',function(){document.getElementsByTagName('script')[1].src='google.com'})");
            }}

提前致谢

1 个答案:

答案 0 :(得分:3)

您永远不会初始化JavascriptExecutor。在这里查看,您将driver指定为null,然后尝试将其强制转换为JavascriptExecutor并且从不对其进行初始化:

private static WebDriver driver = null; // driver is null
public static JavascriptExecutor js = (JavascriptExecutor) driver; // js is null

稍后,您将js分配给driver然后初始化您的驱动程序对象,此处:

JavascriptExecutor js = (JavascriptExecutor) driver; // js is null
driver = new FirefoxDriver(); // driver is now an object

但是当你用js做任何事情时,它仍然是空的:

js.executeScript("window.addEventListener('load',function({document.getElementsByTagName('script')[1].src='google.com'})"); // It's still null here!

您需要正确初始化js对象。顺便说一句,你已经宣布js为班级成员,为什么要立即在主要成员中重新分配?

public static JavascriptExecutor js = (JavascriptExecutor) driver;
JavascriptExecutor js = (JavascriptExecutor) driver; //  This line is unnecessary in main