selenium web driver 使用JS修改input属性

时间:2021-07-27 04:16:24

selenium获取input时候,发现type=”hidden” 的input无法修改value,经牛人指点,可以使用js修改

首先html源文件如下,设置为text 、hidden、submit

 <html>
<head>
<title>this is a test </title>
<script type="text/javascript">
function display_alert()
{
alert("I am an alert box!!")
}
</script>
</head>
<body>
<form action="form_action.jsp" method="get">
<p>Name: <input type="text" id="fn" name="fullname" /></p>
<p>Email: <input type="hidden" id="em" name="email" value="dbyl@dbyl.cn"/></p>
<p><input type="submit" id="su" onclick="display_alert()" value="submit" /></p> </form>
</body>
</html>

在浏览器加载之后如下:

selenium web driver 使用JS修改input属性

这时候email 不能对外显示

使用selenium,代码如下

 import org.openqa.selenium.Alert;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
//import org.openqa.selenium.ie.InternetExplorerDriver;
//import org.openqa.selenium.remote.DesiredCapabilities; public class selenium { /**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub String URL="E:\\2.html";
//set web driver property
System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe");
//create a WebDriver instance
WebDriver driver = new ChromeDriver() ;
driver.manage().window().maximize(); //load the URL
driver.get(URL);
//print current title
System.out.println(driver.getTitle());
//run JS to modify hidden element
((JavascriptExecutor)driver).executeScript("document.getElementById(\"em\").type ='text';");
Thread.sleep(3000);
//run JS and add a alert
((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a alert!\");value=\"Alert\""); //wait for 3 seconds
Thread.sleep(3000); //create a alert instance
Alert alert1=driver.switchTo().alert();
//print alert text
System.out.println(alert1.getText());
//click accept button
alert1.accept(); //create elements
WebElement we=driver.findElement(By.id("fn"));
WebElement su=driver.findElement(By.id("su"));
WebElement em=driver.findElement(By.id("em"));
// input something
we.sendKeys("username test");
Thread.sleep(3000);
//print email tagname
System.out.print("Email isDislayed="+em.isDisplayed()+"\n");
Thread.sleep(3000);
//click submit button
su.click();
Thread.sleep(3000); Alert alert=driver.switchTo().alert();
System.out.print( alert.getText());
alert.accept(); Thread.sleep(3000); //close web browser
driver.quit(); } }

可以通过js修改input的type value,执行js只需要export

import org.openqa.selenium.JavascriptExecutor;

运行结果如下:
selenium web driver 使用JS修改input属性

Starting ChromeDriver (v2.9.248315) on port 30175
this is a test
hello,this is a alert!
Email  isDislayed=true
I am an alert box!!