使用Webdriver执行JS小结

首先,我们使用如下方式初始化driver:

Java代码  收藏代码
  1. WebDriver driver = new FirefoxDriver();  
  2. JavascriptExecutor jse = (JavascriptExecutor)driver;  

1.直接传入Javascript代码

可以直接给jse传入javascript代码:

Java代码  收藏代码
  1. jse.executeScript("window.document.getElementById('jingshou').click()";  

2.传入WebElement执行JS:

Java代码  收藏代码
  1. WebElement element = driver.findElement(By.id("jingshou"));  
  2. jse.executeScript("arguments[0].click();", element);  

又或者:

Java代码  收藏代码
  1. jse.executeScript("arguments[0].onclick=function(){alert('This is my alert!');}", element)  

其中auguments[0]就代表element, 甚至我们可以传入更多的参数,比如

Java代码  收藏代码
  1. WebElement div = driver.findElemnt(By.id("myDiv"));  
  2. jse.executeScript("arguments[0].setAttribute('style', arguments[1])", div, "height: 1000px");  

 通过执行以上代码,我们指定的DIV就新增(修改)了 style {height: 1000px}的属性

 本文出自"lijingshou"博客,转载请务必保留此出处http://lijingshou.iteye.com/blog/2018929

原文地址:https://www.cnblogs.com/testlife007/p/4191288.html