(Python) 将 Playwright Page 对象传递给包装函数的函数装饰器

Posted

技术标签:

【中文标题】(Python) 将 Playwright Page 对象传递给包装函数的函数装饰器【英文标题】:(Python) Function decorator to pass Playwright Page object to wrapped function 【发布时间】:2021-07-13 20:56:44 【问题描述】:

目标:我正在尝试创建一个函数装饰器,它将 Playwright Page(playwright.sync_api._generated.Page) 对象传递给包装函数。

问题:对于大多数函数调用,我将能够返回函数调用返回的值。但是,由于 Playwright 需要 browser.close() 调用,我不能简单地返回 Page 对象。我不确定问题出在 (1) 我定义的函数装饰器,还是 (2) 我对函数装饰器的使用。

我尝试在pytest 固定装置之后为我的装饰器建模。使用pytest,我会做这样的事情:

@pytest.fixture(scope="module")
def playwright_page():
    with sync_playwright() as play:
        browser = play.chromium.launch()
        page = browser.new_page()
        yield page
        browser.close()

然后

def open_google(playwright_page):
    playwright_page.goto("https://google.com")

函数解码器

>>> from playwright.sync_api import sync_playwright
>>> def playwright_page(func):
        def wrapper(*args, **kwargs):
            with sync_playwright() as play:
                browser = play.chromium.launch()
                page = browser.new_page()
                yield page
                browser.close()
        return wrapper

尝试 1

>>> @playwright_page
def open_google():
    page.goto("https://google.com")

    
>>> open_google()
<generator object playwright_page.<locals>.wrapper at 0x0000015C5F6CBC10>

尝试 2

>>> @playwright_page
    def open_google():
        page = next(page)
        page.goto("https://google.com")

    
>>> open_google()
<generator object playwright_page.<locals>.wrapper at 0x0000015C5FDB7F90>

【问题讨论】:

【参考方案1】:

我应该调用func 并传递Page 对象,而不是尝试产生Page 对象,例如pytest 固定装置。

>>> from playwright.sync_api import sync_playwright
>>> def playwright_page(func):
        def wrapper():
            with sync_playwright() as play:
                browser = play.chromium.launch()
                page = browser.new_page()
                results = func(page)
                browser.close()
                return results
        return wrapper


>>> @playwright_page
    def open_google(page):
        page.goto("https://google.com")

【讨论】:

我要补充一点,如果函数的返回值可能很重要,装饰器可能应该在browser.close() 之后执行results = func(page)return results 之类的操作

以上是关于(Python) 将 Playwright Page 对象传递给包装函数的函数装饰器的主要内容,如果未能解决你的问题,请参考以下文章

Python 自动化爬虫利器 Playwright

python+playwright 学习-10.pytest-playwright插件编写测试用例

Python程序员,你还在用selenium吗?试试Playwright吧

Python程序员,你还在用selenium吗?试试Playwright吧

嗨,各位Python程序员,放弃selenium,试试年轻的Playwright如何?

嗨,各位Python程序员,放弃selenium,试试年轻的Playwright如何?