Playwright:无法在第二步中获取浏览器Behave Cucumber Framework

问题描述 投票:0回答:1

这是我的代码,我在 Playwright 上使用 Python,因为我之前使用了 selenium,当你只在第二步中调用

context.driver
时,它会起作用,但在 playwright 上它会返回一个错误

File "features\steps\Login.py", line 14, in click_button
phoneBTN.click()
File "D:\Playwright\venv\Lib\site-packages\playwright\sync_api\_generated.py", line 14764, in click
self._sync(`your`your text` text`
File "D:\Playwright\venv\Lib\site-packages\playwright\_impl\_sync_base.py", line 102, in _sync
raise Error("Event loop is closed! Is Playwright already stopped?")
playwright._impl._errors.Error: Event loop is closed! Is Playwright already stopped?
from behave import given, then
from playwright.sync_api import sync_playwright

@given("the user navigates to the your website")
def navigate_to_your_website(context):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context.page = browser.new_page()
        context.page.goto("https://website.com.pk/")

@then("the website homepage is displayed")
def click_button(context):
        phoneBTN = context.page.locator(".non-auth-section .Continue-with-Phone-Number")
        phoneBTN.click()
        otpBTN = context.page.locator("#otp-number")
        otpBTN.click()

我正在 Playwright 上工作,我已经尝试过不带步骤使用它,它工作正常,当我分步使用它时,它不起作用,请帮忙。

python cucumber playwright playwright-python
1个回答
0
投票

您需要在features文件夹中创建名为environment.py的环境文件,并使用before_all和after_all等行为钩子

希望这段代码对您维护浏览器上下文有帮助

def before_all(context):
context.playwright_instance = sync_playwright().start()  # Start Playwright instance

# Launch Playwright browser instance
browser = context.playwright_instance.chromium.launch(headless=False, slow_mo=1000, channel="chrome")
context.page = browser.new_page()
context.page.set_viewport_size({"width": 1800, "height": 1080})


def after_all(context):
# Closing Playwright browser instance
context.playwright_instance.stop()
© www.soinside.com 2019 - 2024. All rights reserved.