Selenium + FirefoxDriver访问全局javascript对象

时间:2016-05-26 10:58:31

标签: c# selenium selenium-firefoxdriver

我想使用Selenium检查全局对象的值。但到目前为止,我无法使用FirefoxDriver ......

运行类似driver.ExecuteScript("return 1+2");的内容会按预期返回3;运行driver.ExecuteScript("return myObject");可以使用Chrome驱动程序,但在FirefoxDriver中产生null。

以下内容适用于Chrome,但在Firefox中引发异常:

 //driver is either an instance of FirefoxDriver or ChromeDriver
 driver.Url = "https://www.google.com";
 driver.Navigate();
 //gbar is a global object at google.com
 var result = driver.ExecuteScript("return gbar");
 Assert.NotNull(result);

例外:

System.InvalidOperationException : ReferenceError: gbar is not defined (UnexpectedJavaScriptError)
StackTrace: 
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
   at ...

使用Selenium.Webdriver 2.53.0和Firefox开发人员版48.0a2,以及在Win10,.Net 4.6.1上运行的常规Firefox 46.0.1。

3 个答案:

答案 0 :(得分:0)

在您致电public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int num; do { System.out.print("Enter a 2-digit number. The digits should be different. Zero to stop: "); String input = in.next(); try { num = Integer.valueOf(input); if(num == 0) { break; } if(num < 10 || num > 99) { System.out.println("NOT good for your game!"); } else{ if(input.charAt(0) == input.charAt(1)) { System.out.println("NOT good for you game!"); } else { System.out.println("Good for your game! Play!"); } } } catch (NumberFormatException ignored) { System.out.print("Not an integer, try again: "); } } while (true); } 时,似乎尚未定义gbar。我会试着等待它:

ExecuteScript

答案 1 :(得分:0)

尝试运行JQuery代码时,我在FirefoxDriver上遇到同样的问题。

错误:

  

ReferenceError:$未定义(UnexpectedJavaScriptError)firefox   硒

使用相同的代码在ChromeDriver上正常运行

答案 2 :(得分:0)

尝试将自定义功能注入正在运行的网页进行测试时,我遇到了同样的问题。这些功能在chrome驱动程序中可见,但在firefox中不可见。

解决方案是将这些功能注入窗口范围。然后,您可以引用它们而没有“ window”前缀。以下将起作用:

driver.executeScript("window.mystuff = 'somestuff'")
driver.executeScript("return mystuff")