掌握设定页面对象的所有属性的方法,这个例子以设定文本框的可编辑状态和显示长度为目标。
被测试页面HTML代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>设置文本框属性</title> </head> <body> <input type="text" id="text" value="watermelon" size=100>文本框</input> </body> </html>
实例代码:
package cn.om.webdriverapi; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterMethod; public class TestDataPicker { WebDriver driver; String baseURL; @Test public void testdataPicker() { driver.get(baseURL); WebElement textbox = driver.findElement(By.id("text")); setAttribute(textbox, driver, "value", "文本框的文字和长度属性已经被修改"); setAttribute(textbox, driver, "size", "10"); RemoveAttribute(textbox, driver, "size"); } public void setAttribute(WebElement e, WebDriver d, String attributeName, String value) { JavascriptExecutor js = (JavascriptExecutor) d; // 执行JavaScriptdiamante修改页面元素属性。arguments[0]-[2]后面会用e,attributeName,value替换并执行 js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])", e, attributeName, value); } public void RemoveAttribute(WebElement e, WebDriver d, String attributeName) { JavascriptExecutor js = (JavascriptExecutor) d; // 执行JavaScriptdiamante修改页面元素属性。arguments[0]-[2]后面会用e,attributeName,value替换并执行 js.executeScript("arguments[0].removeAttribute(arguments[1])", e, attributeName); } @BeforeMethod public void beforeMethod() { baseURL = "file:///F:/workspace/WebDriver%20API/dataPicker.html"; System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe"); driver = new FirefoxDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } }