尝试:除了:NoSuchFrameException、NoSuchElementException、TimeoutException写错了

问题描述 投票:0回答:1

你能帮我找出我的代码是如何写错的吗?如果元素不存在,我只是尝试传递到下一行,或者只是将某些内容打印到控制台。但是,如果 selenium 无法单击这些元素,它只会抛出一堆错误并停止脚本。

如果元素存在,它会单击它们并正常工作。我正在尝试单击这些元素,但这对我来说不是强制性的。我希望这是有道理的..

本质上只是尝试忽略不可点击的元素,但如果可以点击则单击它们。

        try:
            # First, check if the inqChatStage is available
            WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "inqChatStage")))
            
            # If the inqChatStage is available, try to close the chat
            WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div[aria-label='End Chat']"))).click()
            driver.switch_to.default_content()
            
            # Click the implicit consent box
            WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.implicit_consent span.ups-icon-x"))).click()
        except (NoSuchFrameException, NoSuchElementException, TimeoutException):
            try:
                # If the inqChatStage is not available, try to click the implicit consent box
                driver.switch_to.default_content()
                WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.implicit_consent span.ups-icon-x"))).click()
            except (NoSuchElementException, TimeoutException):
                print("Neither the 'End Chat' option nor the consent box were found. Skipping this part and continuing to the next step.")
                pass
        else:
            # If all the steps above were successful, do the next step
            print("Continuing to the next step...")
python selenium-webdriver
1个回答
0
投票

确保导入了所有必要的模块和异常:

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

这是您提供的代码的稍作修改的版本:

try:
    WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "inqChatStage")))
    WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div[aria-label='End Chat']"))).click()
except (NoSuchFrameException, NoSuchElementException, TimeoutException):
    print("Chat frame or end chat button not found. Trying to consent box.")
finally:
    driver.switch_to.default_content()
try:
    WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.implicit_consent span.ups-icon-x"))).click()
except (NoSuchElementException, TimeoutException):
    print("Consent box not found. Continuing.")
print("Continuing to the next step...")
© www.soinside.com 2019 - 2024. All rights reserved.