selenium常用的API(七)判断元素是否可见

时间:2021-11-26 21:41:48

web页面不可见的元素虽不在页面上显示,但是存在于DOM树中,这些元素webdriver也能找到。

element.is_displayed()方法可以判断元素是否在页面上显示,如果显示返回True,否则返回False。

用于测试的HTML代码:

<html> 
<head> 
<title>HTML中显示与隐藏元素</title> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript"> 
    function showAndHidden1(){ 
        var div1=document.getElementById("div1"); 
        var div2=document.getElementById("div2"); 
        if(div1.style.display=='block') div1.style.display='none'; 
        else div1.style.display='block'; 
        if(div2.style.display=='block') div2.style.display='none'; 
        else div2.style.display='block'; 
    } 
    function showAndHidden2(){ 
        var div3=document.getElementById("div3"); 
        var div4=document.getElementById("div4"); 
        if(div3.style.visibility=='visible') div3.style.visibility='hidden'; 
        else div3.style.visibility='visible'; 
        if(div4.style.visibility=='visible') div4.style.visibility='hidden'; 
        else div4.style.visibility='visible'; 
    } 
</script> 
</head> 
<body> 
    <div>display:元素不占用页面位置</div> 
    <div id="div1" style="display:block;">DIV 1</div> 
    <div id="div2" style="display:none;">DIV 2</div> 
    <input id="button1" type="button" onclick="showAndHidden1();" value="DIV切换" /> 
    <hr> 
    <div>visibility:元素占用页面位置</div> 
    <div id="div3" style="visibility:visible;">DIV 3</div> 
    <div id="div4" style="visibility:hidden;">DIV 4</div> 
    <input id="button2" type="button" onclick="showAndHidden2();" value="DIV切换" /> 
</body> 
</html>

调用API的代码

# encoding=utf-8
import unittest
import time
from selenium import webdriver

class VisitUrl(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome(executable_path="e:\\chromedriver")

    def test_getWebElementIsDisplayed(self):
        # 访问自定义的html网页
        self.driver.get( "http://127.0.0.1/test_visible.html")
        # 通过id="div2"找到第二个div元素
        div2 = self.driver.find_element_by_id("div2")
        # 判断第二个div元素是否在页面上可见
        print div2.is_displayed()

        # 点击第一个切换div按钮,将第二个div显示在页面上
        self.driver.find_element_by_id("button1").click()
        # 再次判断第二个div元素是否可见
        print div2.is_displayed()

        # 通过id="div4"找到第四个div元素
        div4 = self.driver.find_element_by_id("div4")
        # 判断第四个div元素是否在页面上可见
        print div4.is_displayed()

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()