在本文中,田辛老师将详细介绍Playwright的文本框操作, 包括如何获得文本框的值, 以及向文本框中添加单行和多行文本。
田辛老师将用网上的一个测试画面来进行说明:
URL:https://demoqa.com/text-box
F12 查找网站源码,我们可以知道这四个Textbox元素的元素id。
- userName
- userEmail
- currentAddress
- permanentAddress
1 填充单行文本
我们可以使用页面对象的 page.locator()
方法来查找元素,并使用 fill()
方法来输入内容。
# 输入Full Name
page.locator("#userName").fill("Your Name")
2 填充多行文本
对于多行文本来说, 方法和单行文本一致。 只不过需要通过\n
来进行分行。
# 填充地址
page.locator("#currentAddress").fill("Your current address\nYour current address 2\nYour current address 3")
3 获取文本框的值
使用input_value()
方法获得文本框的值。
print(page.locator("#userName").input_value())
print(page.locator("#currentAddress").input_value())
4 完整代码
老规矩, 完整代码示例:
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
# Open new page
page = context.new_page()
# Go to https://demoqa.com/text-box
page.goto("https://demoqa.com/text-box")
# Fill #userName
page.locator("#userName").fill("Your Name")
# Fill #userEmail
page.locator("#userEmail").fill("your.name@yourdomain.com")
# Fill #currentAddress
page.locator("#currentAddress").fill("Your current address\nYour current address 2\nYour current address 3")
# Fill #permanentAddress
page.locator("#permanentAddress").fill("Your permanent address 1\nYour permanent address 2\nYour permanent address 3")
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
执行结果: