python版的Playwright 如何等待
时间: 2024-04-28 13:24:38 浏览: 136
在 Python 版的 Playwright 中,可以使用 `wait_for_selector` 或 `wait_for_timeout` 方法来等待元素出现或等待一段时间。
例如,使用 `wait_for_selector` 方法等待一个元素出现:
```python
from playwright.sync_api import Playwright, sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto('https://www.example.com')
# 等待 id 为 element_id 的元素出现
page.wait_for_selector('#element_id')
browser.close()
```
另外,使用 `wait_for_timeout` 方法等待一段时间:
```python
from playwright.sync_api import Playwright, sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto('https://www.example.com')
# 等待 5 秒钟
page.wait_for_timeout(5000)
browser.close()
```
需要注意的是,如果等待超时,`wait_for_selector` 方法会抛出 `TimeoutError` 异常,而 `wait_for_timeout` 方法则不会抛出异常。
阅读全文