如下如html的頁面代碼
<html> <body> <input type="text" name="text" value="alone"> </body> </html>
使用下列腳本即可改變標簽的屬性
public class Selenium { public static WebDriver jsDriver; @BeforeMethod public void intiDriver(){ System.setProperty("phantomjs.binary.path","D:\\java\\ideaWorkStation\\casual\\src\\main\\resources\\driver\\phantomjs.exe"); jsDriver=new PhantomJSDriver(); jsDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); jsDriver.get("C:\\Users\\win7\\Desktop\\select.html"); } @Test(enabled = true) public void javaScriptExcutor(){ WebElement textEle=jsDriver.findElement(By.name("text")); System.out.println(textEle.getAttribute("value"));//輸入改變之前的值 String jsStrToSetAtt="arguments[0].setAttribute(arguments[1],arguments[2])";//改變屬性的js ((JavascriptExecutor) jsDriver).executeScript(jsStrToSetAtt, textEle, "value", "no alnon"); System.out.println(textEle.getAttribute("value"));//輸入改變后前的值 String jsStrToRemoveAtt="arguments[0].removeAttribute(arguments[1],arguments[2])";//移除屬性的js ((JavascriptExecutor) jsDriver).executeScript(jsStrToRemoveAtt, textEle, "value"); System.out.println(jsDriver.getPageSource());//輸出改變后的頁面代碼 } }
執行腳本后,會看到輸出如下,說明元素的屬性被修改了
alone
no alnon
<html><head></head><body>
<input type="text" name="text">
</body></html>