这种情况下,也需要借助JavaScript 代码完成输入。
HTML代码
<textarea id="id" style="width: 98%" cols="50" rows="5" class="txtarea"> </textarea> ... ...
第一种:
driver.findElement(By.id("id")).sendKeys("需要输入的内容");
1 public static void main(String[] args) throws InterruptedException { 2 System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe"); 3 ChromeOptions Options = new ChromeOptions(); 4 Options.addArguments("user-data-dir=C:\\Users\\happy\\AppData\\Local\\Google\\Chrome\\User Data"); 5 WebDriver driver = new ChromeDriver(Options); 6 driver.manage().window().maximize(); 7 try { 8 driver.get("file:///C:/Users/happy/Desktop/NewFile.html"); 9 driver.findElement(By.id("id")).sendKeys("需要输入的内容"); 10 } finally { 11 Thread.sleep(5000); 12 driver.close(); 13 driver.quit(); 14 } 15 }
第二种:
通过executeScript()执行JavaScript 代码。来实现文本框操作。
1 public static void main(String[] args) throws InterruptedException { 2 System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe"); 3 ChromeOptions Options = new ChromeOptions(); 4 Options.addArguments("user-data-dir=C:\\Users\\happy\\AppData\\Local\\Google\\Chrome\\User Data"); 5 WebDriver driver = new ChromeDriver(Options); 6 driver.manage().window().maximize(); 7 try { 8 driver.get("file:///C:/Users/happy/Desktop/NewFile.html"); 9 String text = "input text"; 10 String js = "var sum=document.getElementById('id'); sum.value='" + text + "';"; 11 ((JavascriptExecutor)driver).executeScript(js); 12 } finally { 13 Thread.sleep(5000); 14 driver.close(); 15 driver.quit(); 16 } 17 }