Selenium WebDriver-判斷頁面中某一元素是否已經顯示,通常用於斷言


判斷界面中某一元素是否已經呈現,多用於斷言,代碼如下:

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

class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #啟動IE瀏覽器
        #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
        self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
        
    def isElementPresent(self, by, value):
        # 從selenium.common.exceptions模塊導入NoSuchElementException異常類
        from selenium.common.exceptions import NoSuchElementException
        try:
            element = self.driver.find_element(by=by, value=value)
        except NoSuchElementException, e:
            # 打印異常信息
            print e
            # 發生了NoSuchElementException異常,說明頁面中未找到該元素,返回False
            return False
        else:
            # 沒有發生異常,表示在頁面中找到了該元素,返回True
            return True
    
    
    def test_isElementPresent(self):
        url = "http://www.sogou.com"
        # 訪問sogou首頁
        self.driver.get(url)
        # 判斷頁面元素id屬性值為“query”的頁面元素是否存在
        res = self.isElementPresent("id", "query")
        if res is True:
            print u"所查找的元素存在於頁面上!"
        else:
            print u"頁面中未找到所需要的頁面元素!"



    def tearDown(self):
        # 退出IE瀏覽器
        self.driver.quit()

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM