我能够看到xpath是否位于try-except()
的{{1}}块中的异常消息。但是,当我向元素添加显式等待时,如果xpath不存在或错误的。
如何在except块中打印错误消息? 如果我运行this,对于第一个能够显示e的东西,则下一个是空白
self.driver.find_element_by_xpath()
答案 0 :(得分:0)
当您使用find_element_by_*
并且万一找不到任何元素时,会抛出NoSuchElementException。
但是,如果您在失败时引发WebDriverWait和expected_conditions一起抛出TimeoutException。
在这一点上,值得一提的是,您应该始终捕获所需的异常,即NoSuchElementException
或TimeoutException
,但不基本异常,即{{1} }保持测试清洁。
一个简单的测试,详细观察Exception
和NoSuchElementException
:
代码块:
TimeoutException
控制台输出:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("start-maximized")
chrome_options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("https://www.google.com/")
try:
driver.find_element_by_xpath("//input[@name='q123']").send_keys("user10391084")
except NoSuchElementException as nse:
print(nse)
print("-----")
print(str(nse))
print("-----")
print(nse.args)
print("=====")
try:
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,"//input[@name='q123']"))).send_keys("user10391084")
except TimeoutException as toe:
print(toe)
print("-----")
print(str(toe))
print("-----")
print(toe.args)
driver.quit()
您可以通过消息从控制台输出中看到,该异常是为 Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@name='q123']"}
(Session info: chrome=75.0.3770.100)
-----
Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@name='q123']"}
(Session info: chrome=75.0.3770.100)
-----
('no such element: Unable to locate element: {"method":"xpath","selector":"//input[@name=\'q123\']"}\n (Session info: chrome=75.0.3770.100)', None, None)
=====
Message:
-----
Message:
-----
('', None, None)
正确定义的,但是<没有为 NoSuchElementException
定义strong>消息部分。因此它变成空白。