无法使用带有多个参数的executioncript selenium方法

时间:2016-12-07 10:11:08

标签: javascript arrays selenium

我试图自动化一个可以创建列表的网站。 通过在文本字段中输入值然后通过在文本字段外单击鼠标来设置值来创建列表。 然后重复上一步,在列表中输入更多元素。 由于我们使用的是Internet Explorer,因此我使用Selenium webdriver和IE。 sendKeys方法非常慢,所以我想使用executioncript方法。

我尝试如下(它不起作用),我想知道是否有人有建议。

代码片段:

//Here I declare an arry with the values for the list to be created

String valores[] = {"18","25","60","71"};

//Here I get the WebElement where I'm going to enter the above values one by one

WebElement searchField = driver.findElement(By.xpath("//label[text()='New value:']/parent::div//input[@type='text']"));

JavascriptExecutor myExecutor6 = ((JavascriptExecutor) driver); 

//Now I’m trying to use a for cycle to enter the values one by one, I need to do this, because this is how the UI works    

for(int i=0; i<valores.length; i++){
      System.out.println(valores[i]);
      Thread.sleep(3000);
/*this part is not working, here what I’m trying to do is: I’m trying to write the value of array valores in position ‘i’ in the text field indicated by the WebElement searchField */
/*I have a javascript error, I do notunderstand what is wrong*/

      myExecutor6.executeScript("var valueToWrite = valores[i].toString();"
+"arguments[0].value = valueToWrite ",searchField, valores[i]);

      Thread.sleep(3000);

//This step clicks somewhere else with the mouse to enter the value,
      driver.findElement(By.xpath("//label[text()='Values:']")).click();
      Thread.sleep(3000);
   }

1 个答案:

答案 0 :(得分:0)

我已经更改了代码,它仍然失败,同样的问题。似乎在javascript中将焦点放在元素上是必要的。这解决了这个问题 参数[0] .focus();

感谢您的帮助。

新代码:

public static void createList(WebDriver driver, String array[]) throws InterruptedException{

String[] values = array.clone(); String iterationNumber; JavascriptExecutor myExecutor = ((JavascriptExecutor) driver); for(int i=0; i<values.length; i++){ System.out.println(values[i]); Thread.sleep(1000); iterationNumber = values[i]; myExecutor.executeScript("arguments[0].focus();"+"arguments[0].value = arguments[1];",driver.findElement(By.xpath("//label[text()='New value:']/parent::div//input[@type='text']")), iterationNumber); Thread.sleep(1000); driver.findElement(By.xpath("//label[text()='Values:']")).click(); Thread.sleep(1000); driver.findElement(By.xpath("//label[text()='New value:']/parent::div/div/div[2]/button")).click(); Thread.sleep(1000); } }
相关问题