如何在python自动化中处理没有这样的异常,

2024-09-29 17:16:53 发布

您现在位置:Python中文网/ 问答频道 /正文

elem = driver.find_element_by_id("msgButtonAffirm")
if elem.is_displayed():
    elem.click()
    print("conform popup is avalable and click")
else:
    print "Pop-up is not visible"

Tags: idbyifisdriverelementfindclick
3条回答

您可以使用find_elements_by_id并检查列表中是否有任何内容

elem = driver.find_elements_by_id("msgButtonAffirm")
if elem and elem[0].is_displayed():
    elem[0].click()
    print("conform popup is avalable and click")
else:
    print("Pop-up is not visible")

您可以导入异常并按以下方式进行处理:

from selenium.common.exceptions import NoSuchElementException

try:
    elem = driver.find_element_by_id("msgButtonAffirm")
    elem.click()
    print("conform popup is avalable and click")
except NoSuchElementException:  
    print("Pop-up is not visible")

你需要注意几件事:

  • 当点击确认弹出窗口时,你不应该把重点放在处理NoSuchElementException
  • 历史上,在大多数情况下,确认弹出窗口驻留在模态对话框中,因此需要归纳WebDriverwait

相关的HTML可以帮助我们更好地分析这个问题。但是,根据上述要点,您需要将WebDriverWaitfor expected_conditions归纳为^{},并且您可以使用以下Locator Strategies之一:

  • 使用CSS_SELECTOR

    try:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#msgButtonAffirm"))).click()
        print ("Pop-up was clickable and clicked")
    except TimeoutException: 
        print ("Pop-up was not clickable")
    
  • 使用XPATH

    try:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='msgButtonAffirm']"))).click()
        print ("Pop-up was clickable and clicked")
    except TimeoutException: 
        print ("Pop-up was not clickable")
    
  • 注意:必须添加以下导入:

    from selenium import webdriver
    from selenium.common.exceptions import TimeoutException
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

相关问题 更多 >

    热门问题