如下如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>
时间: 2024-11-10 00:55:03