Search code examples
pythonplaywrightplaywright-python

How to try clicking on elements in Playwright without try except block?


I have this code:

def try_close_error_popup(self):
        try:
            self.page.locator(
                self.CLOSE, has_text='Close').click(timeout=1200)
        except TimeoutError:
            LOGGER.info('Failed to click close popup button')

I noticed that the try/except blocks make my code to run much slower. Is there a way I can just try finding and element and clicking on it without getting an error?


Solution

  • Try this:

    if (page.is_visible(XPATH)):
        page.click(XPATH)
    

    Or you can make the code cleaner like this:

    try:
        page.click(XPATH)
    except:
        pass