【Python】Playwright 文本框操作

本文介绍了如何使用Playwright库在网页上进行文本框操作,包括填充单行和多行文本,以及获取文本框的值。示例代码展示了在测试页面https://demoqa.com/text-box上对不同ID的文本框进行填充,并通过input_value()方法读取其内容。
摘要由CSDN通过智能技术生成

在本文中,田辛老师将详细介绍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)

执行结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田辛 | 田豆芽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值