Software Testing | Web Automation Testing Artifact Playwright Tutorial (38)

Insert image description here

Introduction

When we use selenium, we can get the attributes of the element, the text value of the element, and the content of the input box. As a more powerful web automation testing tool than selenium, playwright can also implement the element attributes, text value and input box. Content capture and implementation are simpler than selenium. In this article, we will introduce how to use playwright to obtain element attributes, element text values ​​and input box content.

Get element attributes and text values

In selenium, we can get_attribute()get the element attributes and inner_text()the element text value. Now let's introduce how to use playwright to get the element attributes and text value. Let's take the Baidu page as an example, as shown in the figure below:

Insert image description here
We can see that there are multiple a tags in the upper left corner. Now let's get the attributes and text value of a certain tag. The code is as follows:

from playwright.sync_api import sync_playwright



with sync_playwright() as p:
    browser = p.chromium.launch(headless=False, slow_mo=100)
    context = browser.new_context()  # 创建上下文,浏览器实例

    page = context.new_page()  # 打开标签页

    page.goto("https://www.baidu.com/")
    page.wait_for_load_state("networkidle")
    # div 下第一个a标签
    ele1 = page.locator('#s-top-left>a').first
    print(ele1.get_attribute('href'))
    print(ele1.inner_text())

---------
运行脚本,输出结果如下:
http://news.baidu.com
新闻

Get the value in the input box

The value we enter in the input box cannot be displayed in real time on the page, as shown below:

Insert image description here

To get the value entered in the input box, the code is as follows:

from playwright.sync_api import sync_playwright



with sync_playwright() as p:
    browser = p.chromium.launch(headless=False, slow_mo=100)
    context = browser.new_context()  # 创建上下文,浏览器实例

    page = context.new_page()  # 打开标签页

    page.goto("https://www.baidu.com/")
    page.wait_for_load_state("networkidle")
    # 获取输入框的值
    input = page.locator('#kw')
    input.fill('playwright')
    print(input.input_value())
-----------
输出结果如下:
playwright

Summarize

This article mainly introduces the method of using playwright to obtain element attributes, text content and input box content. According to specific needs, we can further expand these operations to perform more complex browser automation tasks. I hope this article is helpful to everyone!

Guess you like

Origin blog.csdn.net/Tester_muller/article/details/132692784