gpt4 book ai didi

python - Python 中的 Selenium 如果元素不存在,如何使用 If - else 代码

转载 作者:行者123 更新时间:2023-11-28 19:33:14 27 4
gpt4 key购买 nike

所有,我需要一些严肃的“简单化”示例来说明如何用 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")

因此,假设存在一个 LINK 是 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 语句。

谢谢,

最佳答案

您可以捕获异常并采取相应措施:

try:
elem = driver.find_element_by_partial_link_text('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!")
except NoSuchElementException:
print("...")

此外,我可能会修改测试以确保该元素确实是“可点击的”:

if elem.is_displayed() and elem.is_enabled():

关于python - Python 中的 Selenium 如果元素不存在,如何使用 If - else 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39147245/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com