Python Selenium WebDriverWait,如何以不同的方式处理不同的异常?

2024-09-29 22:34:01 发布

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

问题:在了解如何在Python Selenium中实现WebDriverWait方法时遇到了一些问题

我不想在NoTouchElementException上做任何事情,只想在StaleElementReference、ElementNotInteractiable、ElementClickIntercepted和任何新的弹出窗口上使用WebDriverWait

下面的内容对我来说只适用于StaleElementReference,但是如果我想合并除NoTouchElement之外的所有类似异常,我该怎么办?我相信可能会出现的不仅仅是这个3

def click(selector):
    try:
        elem = browser.find_element_by_css_selector(selector)
        elem.click()      
    except NoSuchElementException:
        pass
    except StaleElementReferenceException:
        elem = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
        elem.click()

编辑:添加了来自@BapRx解决方案的错误消息

    elem.click()
    self._execute(Command.CLICK_ELEMENT)
    return self._parent.execute(command, params)
    self.error_handler.check_response(response)
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <span>...</span> is not clickable at point (730, 523). Other element would receive the click: <div id="JDCol" class="noPad">...</div>
  (Session info: chrome=87.0.4280.88)


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
    click(company_tab_selector) #Company Tab
    elem.click()
    self._execute(Command.CLICK_ELEMENT)
    return self._parent.execute(command, params)
    self.error_handler.check_response(response)
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <span>...</span> is not clickable at point (730, 523). Other element would receive the click: <div id="JDCol" class="noPad">...</div>
  (Session info: chrome=87.0.4280.88)'

Tags: theselfdivbrowserexecuteresponseexceptionelement
2条回答

您可以这样做:

try:
    elem = browser.find_element_by_css_selector(selector)
    elem.click()      
except NoSuchElementException:
    pass
except Exception as e:
    print(e) # You can still log the error
    elem = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
    elem.click()

这对我很有用:

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait

def wait_for(web_driver, web_element: str, delay=60) -> bool:
try:
    WebDriverWait(web_driver, delay).until(
        ec.presence_of_element_located((By.XPATH, web_element)))
    return True
except TimeoutException as e:
    return False

相关问题 更多 >

    热门问题