|
在用selenium 1.X的时候常常会用到getEval()方法来执行一段js脚本来对页面进行处理,以处理一些遇到的问题。当然selenium webdriver也提供这样的一个方法:executeScript()
CODE:
- <font size="4">import org.openqa.selenium.JavascriptExecutor;
- import org.openqa.selenium.WebDriver;
-
- public class SimpleExample {
-
-
- public staticvoid main(String[] args) {
- WebDriver driver = new FirefoxDriver();
-
- ((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a alert!\")");
- }
-
- }</font>
复制代码 CODE:
- <font size="4">import org.openqa.selenium.JavascriptExecutor;
- import org.openqa.selenium.WebDriver;
-
- public class SimpleExample {
-
-
- public static void main(String[] args) {
- WebDriver driver = new FirefoxDriver();
-
- ((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a alert!\")");
- }
-
- }</font>
复制代码 上面是一个最简单的例子,打开一个浏览器,然后弹层一个alert框。注意这里的driver要被强制转换成JavascriptExecutor。
下面演示在打开51.com首页如何得到帐号输入框中显示的字符,并打印输出。
CODE:
- <font size="4">import org.openqa.selenium.JavascriptExecutor;
- import org.openqa.selenium.WebDriver;
-
- public class FirstExampe {
-
- public staticvoid main(String[] args) {
- WebDriver driver = new FirefoxDriver();
- driver.get("http://www.51.com");
- String js = "var user_input = document.getElementById(\"passport_51_user\").title;return user_input;";
-
- String title = (String)((JavascriptExecutor)driver).executeScript( js);
- System.out.println(title);
- }
-
- }</font>
复制代码 CODE:
- <font size="4">import org.openqa.selenium.JavascriptExecutor;
- import org.openqa.selenium.WebDriver;
-
- public class FirstExampe {
-
-
- public static void main(String[] args) {
- WebDriver driver = new FirefoxDriver();
- driver.get("http://www.51.com");
- String js = "var user_input = document.getElementById(\"passport_51_user\").title;return user_input;";
-
- String title = (String)((JavascriptExecutor)driver).executeScript( js);
- System.out.println(title);
- }
-
- }</font>
复制代码 输出结果为:
CODE:
- <font size="4">用户名/彩虹号/邮箱</font>
复制代码
|
|