前言
在定位元素的時候,經常會遇到各種異常,為什么會發生這些異常,遇到異常又該如何處理呢?
本篇通過學習selenium的exceptions模塊,了解異常發生的原因。
一、發生異常
1.打開百度首頁,F12查看“百度一下”的屬性
<input type="submit" value="百度一下" id="su" class="btn self-btn bg s_btn">
2.為了故意讓它定位失敗,我在元素屬性后加上xx
3.執行代碼,報錯。程序在查找元素的這行發生了中斷,不會繼續執行click事件了
參考代碼:
# coding:utf-8
from selenium import webdriver
driver=webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.find_element_by_id("suxx").click()
運行結果:
Traceback (most recent call last):
File "E:/study/selenium_study/a825.py", line 5, in <module>
driver.find_element_by_id("suxx").click()
File "D:\Program Files\python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "D:\Program Files\python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "D:\Program Files\python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "D:\Program Files\python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="suxx"]"}
(Session info: chrome=84.0.4147.135)
二、捕獲異常
1.為了讓程序繼續執行,我們可以用try...except...捕獲異常。捕獲異常后可以打印出異常原因,以便於分析異常原因。
2.從運行結果看出,發生異常原因是:NoSuchElementException
3.從selenium.common.exceptions 導入 NoSuchElementException類
# coding:utf-8
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
driver=webdriver.Chrome()
driver.get("https://www.baidu.com")
try:
s=driver.find_element_by_id("suxx")
except NoSuchElementException as msgs:
print("查找元素異常:{}".format(msgs))
else:
s.click()
運行結果:
查找元素異常:Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="suxx"]"}
(Session info: chrome=84.0.4147.135)
三、selenium常見異常
1.NoSuchElementException:沒有找到元素
2.NoSuchFrameException:沒有找到iframe
3.NoSuchWindowException:沒找到窗口句柄handle
4.NoSuchAttributeException:屬性錯誤
5.NoAlertPresentException:沒找到alert彈出框
6.ElementNotVisibleException:元素不可見
7.ElementNotSelectableException:元素沒有被選中
8.TimeoutException:查找元素超時
四、可以不導入異常類,直接寫Exception
# coding:utf-8
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
driver=webdriver.Chrome()
driver.get("https://www.baidu.com")
try:
s=driver.find_element_by_id("suxx")
except Exception as msgs:
print("查找元素異常:{}".format(msgs))
else:
s.click()
運行結果:
查找元素異常:Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="suxx"]"}
(Session info: chrome=85.0.4183.83)
