一、显示\隐藏的元素

在使用selenium进行自动化时,可能会遇到隐藏的元素,列如下图中,我们点击“隐藏按钮”,输入框就会被隐藏,点击“显示按钮”,输入框就会显示出来.

         

输入框在显示和隐藏时,标签属性会发生变化:

例如输入框隐藏时diaplay的属性值为“none”:

显示时diaplay的属性值为“block”:

注意:

因为开发人员在开发网站时对于隐藏元素时使用的方法不同,可能就会导致以下两种结果:

1、不管元素是否在页面上是否被隐藏我们都可以使用相同的路径来操作他,但是元素隐藏时就算查找到我们也无法操作它。

2、当元素为隐藏状态时,我们无法定位到它。

 

二、实例演示

以下演示操作以图中页面为例(图中的页面是本地的网页,小伙伴们如果需要可以加入555191854下载或者找其它的网站进行练习):

 1 package basicweb;
 2 
 3 import java.util.concurrent.TimeUnit;
 4 
 5 import org.junit.jupiter.api.AfterEach;
 6 import org.junit.jupiter.api.BeforeEach;
 7 import org.junit.jupiter.api.Test;
 8 import org.openqa.selenium.By;
 9 import org.openqa.selenium.WebDriver;
10 import org.openqa.selenium.WebElement;
11 import org.openqa.selenium.chrome.ChromeDriver;
12 
13 class ElementDisplayed {
14     
15     WebDriver driver;
16     String url;
17     
18     @BeforeEach
19     void setUp() throws Exception {
20         driver = new ChromeDriver();
21         url = "C:\\Users\\acer\\eclipse-workspace\\SeleniumPractise\\PracticePage.html";
22         driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
23         driver.manage().window().maximize();
24         driver.get(url);
25     }
26 
27     @Test
28     void test() throws Exception {
29         WebElement el = driver.findElement(By.id("displayed-text"));
30 //        isDisplayed可以判断文本框是否显示
31         System.out.println("文本框是否显示:"+el.isDisplayed());
32         
33         Thread.sleep(2000);
34 //        点击隐藏按钮
35         WebElement hideButton = driver.findElement(By.id("hide-textbox"));
36         hideButton.click();
37         System.out.println("点击了隐藏按钮");
38         System.out.println("文本框是否显示:"+el.isDisplayed());
39 
40         Thread.sleep(2000);
41 //        点击显示按钮
42         WebElement showButton = driver.findElement(By.id("show-textbox"));
43         showButton.click();
44         System.out.println("点击了显示按钮");
45         System.out.println("文本框是否显示:"+el.isDisplayed());
46         }
47     
48     @AfterEach
49     void tearDown() throws Exception {
50         Thread.sleep(2000);
51         driver.quit();
52     }
53 
54 
55 }

 

 如果有不明白的小伙伴可以加群“555191854”问我,群里都是软件行业的小伙伴可以相互一起学习讨论。

 

posted on 2019-05-10 17:03  时光以北暮南城  阅读(316)  评论(0)    收藏  举报