1、1.直接傳入Javascript代碼,定位元素
js可以點擊頁面上不顯示暫時隱藏(比如下拉列表),但是html文件中存在的屬性
WebDriver driver = new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor)dr;
比如:http://www.globebuy.com/search/searchNew.jhtml?query=minions&categoryid=250007 頁面中登錄下的my Account
js.executeScript("window.document.getElementById('myAccount').click()";
2、傳入WebElement執行JS,對元素進行操作
此處可以通過webdriver的N種定位方式來定位 id/name/class/linktext/partlinktext/xpath/css等
- WebElement element = driver.findElement(By.linkText("Electronics")); //
- js.executeScript("arguments[0].click();", element);
3、為元素新增點擊事件
之前元素沒有onclick()事件,此處是新增
WebElement e = driver.findElement(By.xpath(".//*[@id='lg']/img"));
js.executeScript("arguments[0].onclick=function(){window.open('http://www.sina.com')}",e);
4、修改元素屬性
- WebElement e= driver.findElemnt(By.id("inputnumber"));
- js.executeScript("arguments[0].setAttribute('style', arguments[1])", e, "height: 800px");
5、 新增元素屬性
待定
6、 刪除元素屬性
- WebElement e= driver.findElemnt(By.id("inputnumber"));
- js.executeScript("arguments[0].removeAttribute('style')",e);
7、 得到元素屬性
- WebElement e= driver.findElemnt(By.id("inputnumber"));
- js.executeScript("document.getElementById("myDiv")",e);