告诉你playwright 不使用with sync_playwright() as编写脚本的新方法

告诉你playwright 不使用with sync_playwright() as编写脚本的新方法_第1张图片

大家都知道playwright代码的标准写法是:

with sync_playwright() as p:

    browser = p.chromium.launch(channel="chrome", headless=False)
    page = browser.new_page()
    page.goto("http://www.baidu.com")
    print(page.title())
    browser.close()

with sync_playwright() as 是python中的重要知识点上下文管理器(context manager)。上下文管理器用于规定某个对象的使用范围。一旦进入或者离开该使用范围,会有特殊操作被调用,它的语法形式就是with...as...

详情可以参考文章

以playwright脚本为例,详解Python with as处理异常的原理-CSDN博客

我们一定要用上下文管理器这种形式编写代码吗?当然不是!我们也可以这样设计代码:

playwright2 = sync_playwright().start() #用这句开头
print(type(playwright2)) #输出
browser2= playwright2.chromium.launch(headless=False)
page2 = browser2.new_page()
page2.goto("http://www.baidu.com")
print(page2.title())
browser2.close()
playwright2.stop()  #用这句结尾

可能有的人要问我是怎么知道这种写法的呢?我是在看playwright源码时无意间看到的,哈哈!

源码位置 \playwright\sync_api\_generated.py文件中的 class Playwright(SyncBase)的stop方法

def stop(self) -> None:
    """Playwright.stop

    Terminates this instance of Playwright in case it was created bypassing the Python context manager. This is useful
    in REPL applications.

    ```py
    >>> from playwright.sync_api import sync_playwright

    >>> playwright = sync_playwright().start()

    >>> browser = playwright.chromium.launch()
    >>> page = browser.new_page()
    >>> page.goto(\"http://whatsmyuseragent.org/\")
    >>> page.screenshot(path=\"example.png\")
    >>> browser.close()

    >>> playwright.stop()
    ```
    """

我的每一篇文章都希望帮助读者解决实际工作中遇到的问题!如果文章帮到了您,劳烦点赞、收藏、转发!您的鼓励是我不断更新文章最大的动力!

 
  

你可能感兴趣的:(Playwright,Python,自动化测试,前端,测试工具)