填写对话框表单。Python Playwright

0 投票
1 回答
31 浏览
提问于 2025-04-13 19:59

我有一个用Python写的脚本,使用了Playwright这个工具。我想在一个对话框里填入一个提示框的内容,但我的脚本只是在按钮上点击一下,打开了提示框,然后立刻就接受了这个提示框,没有把prompt_text这个变量的内容填进去。我尝试去处理这个问题,具体可以参考这个链接:https://practice-automation.com/popups/

提示框的方法


def prompt(self, prompt_text) -> None:
    self.page.once("dialog", lambda dialog: dialog.accept(prompt_text))
    self.popup_locator.prompt_trigger_btn.click()
    time.sleep(1)
    if prompt_text == "":
        expect(self.popup_locator.prompt_result_p).to_be_visible()
        expect(self.popup_locator.prompt_result_p).to_have_text("Fine, be that way...")
    else:
        expect(self.popup_locator.prompt_result_p).to_be_visible()
        expect(self.popup_locator.prompt_result_p).to_have_text(f"Nice to meet you, {prompt_text}!")
    self.popup_locator.prompt_trigger_btn.click()
    self.page.once("dialog", lambda dialog: dialog.dismiss())
    expect(self.popup_locator.prompt_result_p).to_have_text("Fine, be that way...")

测试文件:

def test_close(set_up):
    popup_obj = Popup_page(set_up)
    popup_obj.goto()
    popup_obj.prompt("Dupa")
    popup_obj.prompt("")

我还有一个包含定位器的文件,但打开对话框的按钮是可以工作的。就是没有把提示框里的输入框填上内容。

1 个回答

0

你没有提供完整的可运行代码,所以很难判断哪里出问题了。

我在下面写了一个示例测试代码,基于你的代码,你能试着把它反映到你的代码中吗?这个代码在点击按钮前后会截图,这样你就可以看到它是怎么工作的。

import datetime

from playwright.sync_api import Page, expect


def get_screenshot_file_path(type: str):
    current = datetime.datetime.now()
    return "screenshots/" + current.strftime("%Y%m%d-%H%M%S-%f") + "-" + type + ".png"


def prompt(page: Page, prompt_text) -> None:
    page.once("dialog", lambda dialog: dialog.accept(prompt_text))
    # popup_locator.prompt_trigger_btn.click()
    prompt_trigger_locator = page.get_by_role("button", name="Prompt Popup")
    page.screenshot(path=get_screenshot_file_path("before-first-prompt-click"))
    prompt_trigger_locator.click()
    page.screenshot(path=get_screenshot_file_path("after-first-prompt-click"))

    # time.sleep(1)
    page.wait_for_timeout(1_000)

    prompt_result_locator = page.locator("#promptResult")
    expect(prompt_result_locator).to_be_visible()

    if prompt_text == "":
        expect(prompt_result_locator).to_have_text("Fine, be that way...")
    else:
        expect(prompt_result_locator).to_have_text(f"Nice to meet you, {prompt_text}!")

    page.once("dialog", lambda dialog: dialog.dismiss())
    # popup_locator.prompt_trigger_btn.click()
    page.screenshot(path=get_screenshot_file_path("before-second-prompt-click"))
    prompt_trigger_locator.click()
    page.screenshot(path=get_screenshot_file_path("after-second-prompt-click"))

    expect(page.locator("#promptResult")).to_have_text("Fine, be that way...")


def test_close(page: Page):
    page.goto("https://practice-automation.com/popups/")
    prompt(page, "Dupa")
    prompt(page, "")

撰写回答