首页 > 技术文章 > java使用Selenium操作谷歌浏览器学习笔记(三)键盘操作

davidFB 2021-08-04 15:46 原文

我们用Selenium打开网页后,可能需要在输入框输入一些内容等等,这时候就需要键盘操作了

使用sendKEys进行键盘操作,在bing的搜索框中输入内容并点击跳转

 1 import org.openqa.selenium.By;
 2 import org.openqa.selenium.Keys;
 3 import org.openqa.selenium.WebDriver;
 4 import org.openqa.selenium.WebElement;
 5 import org.openqa.selenium.chrome.ChromeDriver;
 6 import org.openqa.selenium.interactions.Actions;
 7 
 8 public class Test {
 9     public static void main(String[] args) {
10         System.setProperty("webdriver.chrome.driver", "D:\\New folder\\chromedriver_win32/chromedriver.exe");
11         WebDriver webDriver = new ChromeDriver();
12         try {
13             String s = "https://cn.bing.com/";
14 
15             Actions action = new Actions(webDriver);
16 
17             webDriver.get(s);
18 
19             Thread.sleep(1000);
20 
21             WebElement element = webDriver.findElement(By.id("sb_form_q"));
22 
23             element.sendKeys("搜索" + Keys.ENTER);
24 
25         } catch (InterruptedException e) {
26             e.printStackTrace();
27         } finally {
28         }
29     }
30 }

使用action进行键盘操作,在bing的搜索框中输入内容并点击跳转

 1 import org.openqa.selenium.By;
 2 import org.openqa.selenium.Keys;
 3 import org.openqa.selenium.WebDriver;
 4 import org.openqa.selenium.WebElement;
 5 import org.openqa.selenium.chrome.ChromeDriver;
 6 import org.openqa.selenium.interactions.Action;
 7 import org.openqa.selenium.interactions.Actions;
 8 
 9 public class Test {
10     public static void main(String[] args) {
11         System.setProperty("webdriver.chrome.driver", "D:\\New folder\\chromedriver_win32/chromedriver.exe");
12         WebDriver webDriver = new ChromeDriver();
13         try {
14             String s = "https://cn.bing.com/";
15 
16             Actions actionBuilder = new Actions(webDriver);
17 
18             webDriver.get(s);
19 
20             Thread.sleep(1000); //等待一秒钟,直到页面动态渲染完毕
21 
22             WebElement element = webDriver.findElement(By.id("sb_form_q")); //已知搜索框的id
23 
24             element.clear();//清除搜索框的内容
25 
26             Action action= actionBuilder
27                     .keyDown(Keys.SHIFT)
28                     .sendKeys(element,"abcd") //输入大写的字母
29                     .keyUp(Keys.SHIFT)
30                     .sendKeys("abcd")
31                     .sendKeys(Keys.ENTER)
32                     .build();
33 
34             action.perform();
35 //            element.sendKeys("搜索" + Keys.ENTER);
36 
37         } catch (InterruptedException e) {
38             e.printStackTrace();
39         } finally {
40 //            webDriver.close();
41         }
42     }
43 }

 

推荐阅读