Python Playwright 文本框操作技巧

在本文中,将详细介绍Playwright的文本框操作, 包括如何获得文本框的值, 以及向文本框中添加单行和多行文本。

田辛老师将用网上的一个测试画面来进行说明:

URL:https://demoqa.com/text-box

-1

F12 查找网站源码,我们可以知道这四个Textbox元素的元素id。

  • userName
  • userEmail
  • currentAddress
  • permanentAddress

1 填充单行文本

我们可以使用页面对象的 page.locator() 方法来查找元素,并使用 fill() 方法来输入内容。

  1. # 输入Full Name
  2. page.locator(“#userName”).fill(“Your Name”)

2 填充多行文本

对于多行文本来说, 方法和单行文本一致。 只不过需要通过\n来进行分行。

  1. # 填充地址
  2. page.locator(“#currentAddress”).fill(“Your current address\nYour current address 2\nYour current address 3”)

3 获取文本框的值

使用input_value()方法获得文本框的值。

  1. print(page.locator(“#userName”).input_value())
  2. print(page.locator(“#currentAddress”).input_value())

4 完整代码

老规矩, 完整代码示例:

  1. from playwright.sync_api import Playwright, sync_playwright, expect
  2. def run(playwright: Playwright) -> None:
  3.      browser = playwright.chromium.launch(headless=False)
  4.      context = browser.new_context()
  5.      # Open new page
  6.      page = context.new_page()
  7.      # Go to https://demoqa.com/text-box
  8.      page.goto(“https://demoqa.com/text-box”)
  9.      # Fill #userName
  10. page.locator(“#userName”).fill(“Your Name”)
  11.      # Fill #userEmail
  12.      page.locator(“#userEmail”).fill(“your.name@yourdomain.com”)
  13.      # Fill #currentAddress
  14.      page.locator(“#currentAddress”).fill(“Your current address\nYour current address 2\nYour current address 3”)
  15.      # Fill #permanentAddress
  16.      page.locator(“#permanentAddress”).fill(“Your permanent address 1\nYour permanent address 2\nYour permanent address 3”)
  17.      # ———————
  18.      context.close()
  19.      browser.close()
  20. with sync_playwright() as playwright:
  21.      run(playwright)

执行结果:

-2

到此这篇关于python Playwright 文本框操作的文章就介绍到这了,更多相关Python Playwright 文本框内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论