总之,我需要一些严肃的“简化”示例来说明如何用Python编写代码,以便在元素存在或不存在时执行某些操作。我对程序设计还不太熟悉,我已经看了一天的文章,但我似乎想不出来。。。。
这就是我要做的。from selenium.common.exceptions import NoSuchElementException, staleElementReferenceException
elem = driver.find_element_by_partial_link_text('Create Activity')
print("Searching for Create Activity.")
if elem.is_displayed():
elem.click() # this will click the element if it is there
print("FOUND THE LINK CREATE ACTIVITY! and Clicked it!")
else:
print ("NO LINK FOUND")
因此,如果存在一个链接,它是element_by_partial_LINK_text('Create Activity')
我得到了正确的回应。。。
正在搜索创建活动。
找到链接创建活动!然后点击它!
我的问题是没有匹配的链接element_by_partial_link_text('Create Activity')
我不明白我在else陈述中所期望的。
print ("NO LINK FOUND")
我得到。。。Traceback (most recent call last):
File "", line 1, in
File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 341, in find_element_by_partial_link_text
return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 745, in find_element
{'using': by, 'value': value})['value']
File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"Create Activity"}
如何在Python中获取selenium来将此异常或错误转换为不停止脚本并仅处理ELSE语句。
谢谢