Python Playwright 文本框操作技巧
在本文中,将详细介绍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)
执行结果:
到此这篇关于python Playwright 文本框操作的文章就介绍到这了,更多相关Python Playwright 文本框内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
发表评论