selenium测试(Java)--执行JS(十八)

 

1.  操作滚动条

 1 package com.test.js;
 2 
 3 import org.openqa.selenium.By;
 4 import org.openqa.selenium.Dimension;
 5 import org.openqa.selenium.JavascriptExecutor;
 6 import org.openqa.selenium.WebDriver;
 7 import org.openqa.selenium.firefox.FirefoxDriver;
 8 
 9 public class WindowScroll {
10 
11     public static void main(String[] args) {
12         WebDriver driver = new FirefoxDriver();
13         driver.get("http://www.baidu.com");
14         driver.manage().window().setSize(new Dimension(600, 600));
15 
16         waitTime(3000);
17         driver.findElement(By.cssSelector("#kw")).sendKeys("selenium");
18         driver.findElement(By.cssSelector("#su")).click();
19 
20         waitTime(3000);
21         String js = "window.scrollTo(100,450);";
22         ((JavascriptExecutor) driver).executeScript(js);
23 
24         waitTime(5000);
25         driver.quit();
26 
27     }
28 
29     static public void waitTime(int time) {
30 
31         try {
32             Thread.sleep(time);
33         } catch (InterruptedException e) {
34             // TODO Auto-generated catch block
35             e.printStackTrace();
36         }
37     }
38 }

2.在textarea中输入内容

 

 1 package com.test.js;
 2 
 3 import org.openqa.selenium.By;
 4 import org.openqa.selenium.JavascriptExecutor;
 5 import org.openqa.selenium.WebDriver;
 6 import org.openqa.selenium.firefox.FirefoxDriver;
 7 
 8 public class TextareaInput {
 9 
10     public static void main(String[] args) {
11         WebDriver driver = new FirefoxDriver();
12         driver.get("file:///D:/10-selenium/workspace/SeleniumTest/src/com/test/js/textarea.html");
13         driver.manage().window().maximize();
14 
15         driver.findElement(By.cssSelector("#id")).sendKeys("input text----");
16 
17         // 利用JS来输入内容
18         waitTime(5000);
19         String text = "input by js";
20         String js = "var sum = document.getElementById('id'); sum.value='" + text + "';";
21         System.out.println(js);
22         ((JavascriptExecutor) driver).executeScript(js);
23 
24     }
25 
26     static public void waitTime(int time) {
27 
28         try {
29             Thread.sleep(time);
30         } catch (InterruptedException e) {
31             // TODO Auto-generated catch block
32             e.printStackTrace();
33         }
34     }
35 }

 

 

参考:

http://www.cnblogs.com/tobecrazy/p/4817946.html

 

posted @ 2016-07-16 18:44  月色深潭  阅读(5828)  评论(0编辑  收藏  举报