playwright不关闭浏览器 python
时间: 2023-10-15 22:07:58 浏览: 272
Playwright是一个Python库,可通过单个API自动化Chromium,Firefox和WebKit浏览器-Python开发
您可以在使用Playwright的过程中,使用如下代码段来避免自动关闭浏览器:
```python
# 在Playwright运行结束后,不自动关闭浏览器
from playwright.sync_api import Playwright, Browser, BrowserContext, Page
def my_test(playwright: Playwright) -> None:
browser: Browser = playwright.chromium.launch()
context: BrowserContext = browser.new_context()
page: Page = context.new_page()
page.goto('https://www.baidu.com')
# do something
context.close() #手动关闭上下文,但是浏览器实例不会被关闭
#主函数
with playwright.sync_playwright() as playwright:
my_test(playwright)
```
这样,运行完毕后虽然上下文被关闭了,但是浏览器实例会保持打开。 如果你需要手动关闭浏览器,你可以添加下面的代码:
```python
# 手动关闭浏览器实例
browser.close()
```
阅读全文