selenium—用NoSuchElementException异常判断页面元素是否存在

一、知识补充

1、find_element的一种使用方法:

find_element(by=方法,value=值)

例如: find_element(by="id",value="query")

2、selenium.common.exceptions模块

from selenium.common.exceptions import NoSuchElementException

使用WebDriver实施自动化过程中抛出的所有异常都是用selenium.common.exceptions模块导入的

例如NoSuchElementException、TimeoutException

二、代码示例

# coding=UTF-8
#20.判断页面元素是否存在
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from selenium import webdriver
import unittest
import time
from selenium.common.exceptions import NoSuchElementException

class Case20(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome()

    def isElementPresent(self, a ,b):
        try:
            element = self.driver.find_element(by= a, value= b)
        except NoSuchElementException,e:
            print e
            return False
        else:
            return True

    def test_isElementPresent(self):
        url = "https://www.sogou.com"
        self.driver.get(url)
        res = self.isElementPresent("id", "query")
        if res is True:
            print u"元素在页面上"
        else:
            print u"元素不在页面上"
            
    def tearDown(self):
        self.driver.quit()

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



原文地址:https://www.cnblogs.com/erchun/p/11806911.html