Master the method of setting all the properties of the page object. This example aims to set the editable state and display length of the text box.
Tested page HTML code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Set textbox properties</title> </head> <body> <input type="text" id="text" value="watermelon" size=100>文本框</input> </body> </html>
Example code:
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", "The text and length attributes of the textbox have been modified"); setAttribute(textbox, driver, "size", "10"); RemoveAttribute(textbox, driver, "size"); } public void setAttribute(WebElement e, WebDriver d, String attributeName, String value) { JavascriptExecutor js = (JavascriptExecutor) d; // Execute JavaScriptdiamante to modify page element properties. arguments[0]-[2] will be replaced with e, attributeName, value and executed later 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; // Execute JavaScriptdiamante to modify page element properties. arguments[0]-[2] will be replaced with e, attributeName, value and executed later 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(); } }