使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM