使用场景:
1、元素只有在某一特定情况下才会出现
2、元素定位不到
使用方法:
try:
except exceptions.NoSuchElementException:
举例说明:
# _._ coding=utf-8 _._ """ :author: 花花测试 :time: 2017.05.08 :content: 处理元素定位的异常情况 """ from selenium import webdriver from datetime import datetime from selenium.common import exceptions import random import time """ http://www.kgc.cn/personal_management/17087.shtml:这个课程不是直播课 http://www.kgc.cn/java/25349.shtml:这个课程是直播课 """ driver = webdriver.Chrome() driver.get('http://www.kgc.cn/personal_management/17087.shtml') try: end_time = driver.find_element_by_xpath( '/html/body/div[2]/div/div/div[2]/div[2]/div[1]/div[2]/div[3]/div/span[2]').text now_time = datetime.now().strftime('%Y-%m-%d %H:%M') print('直播结束时间为:{0}'.format(end_time)) print('当前时间为:{0}'.format(now_time)) time.sleep(1) if end_time >= now_time: print('这个课程是直播未开始或者是直播已经开始的课程') else: print('这个课程是直播已结束的课程') except exceptions.NoSuchElementException: print('您选择的这节课程不是直播课') driver.quit() print('测试结束')
说明:
1、我的脚本都是以课工场为例,如果有什么不明白的地方,欢迎大家留言,我看的话会及时给大家解答
2、辛苦原创,转载请注明出处