How can I handle the wait_for_selector function's TimeoutError in Playwright-python?

Viewed 1955

I want to use Except TimeoutError to handle the timeout problem. But the script always throws me a TimeoutError, not print a message as I planed.

Here is my code:

try:
    await page.wait_for_selector("#winiframe_main", timeout=10000, state='detached')
    print("The frame is detached.")
except TimeoutError:
    print("The frame is not detached")

Is there anything wrong with my code?

2 Answers

You have to import TimeoutError from playwright to catch this exception:

from playwright.async_api import async_playwright, TimeoutError

It kept on throwing an error with the imported TimeoutError, so I left it out all together. Plus had to disable a flake8 error with # noqa

try:
  // some selector that might fail
  page.locator("whatever")
except: # noqa: E722
  print("Not today")
```
Related