【Python】使用Playwright断言方法验证网页和Web应用程序状态

作为测试框架,Playwright 提供了一系列断言方法,您可以使用它们来验证网页和 Web 应用程序的状态。在这篇博客中,田辛老师将介绍 Playwright 中可用的各种断言方法,并为每种方法提供示例。

  1. assert page.url() == 'expected_url' :此断言方法验证页面的当前 URL 是否与预期的 URL 匹配。示例代码:

    def test_url():
        page.goto('https://www.example.com')
        assert page.url() == 'https://www.example.com'
    
  2. assert page.title() == 'expected_title' :此断言方法验证页面的当前标题是否与预期标题匹配。示例代码:

    def test_title():
        page.goto('https://www.example.com')
        assert page.title() == 'Example Domain'
    
  3. assert page.is_visible(selector) :此断言方法验证与指定 CSS 选择器匹配的元素在页面上是否可见。示例代码:

def test_visibility():
    page.goto('https://www.example.com')
    assert page.is_visible('#content')
  1. assert page.is_disabled(selector) :此断言方法验证页面上是否禁用了与指定 CSS 选择器匹配的元素。示例代码:

    def test_disabled():
        page.goto('https://www.example.com')
        assert page.is_disabled('#submit')
    
  2. assert page.is_enabled(selector) :此断言方法验证页面上是否启用了与指定 CSS 选择器匹配的元素。示例代码:

def test_enabled():
    page.goto('https://www.example.com')
    assert page.is_enabled('#submit')
  1. assert page.is_checked(selector) :此断言方法验证页面上是否选中了与指定 CSS 选择器匹配的复选框或单选按钮。示例代码:
```python
def test_checked():
    page.goto('https://www.example.com')
    assert page.is_checked('#checkbox')
```
  1. assert page.text_content(selector) == 'expected_text' :此断言方法验证与指定 CSS 选择器匹配的元素的文本内容是否与预期文本匹配。示例代码:
def test_text_content():
    page.goto('https://www.example.com')
    assert page.text_content('#content') == 'Welcome to Example Domain'
  1. assert page.inner_html(selector) == 'expected_html' :此断言方法验证与指定 CSS 选择器匹配的元素的内部 HTML 是否与预期的 HTML 匹配。示例代码:

    def test_inner_html():
        page.goto('https://www.example.com')
        assert page.inner_html('#content') == '<div id="content">Welcome to Example Domain</div>'
    
  2. assert page.outer_html(selector) == 'expected_html' :此断言方法验证与指定 CSS 选择器匹配的元素的外部 HTML 是否与预期的 HTML 匹配。示例代码:

    def test_outer_html():
    page.goto('https://www.example.com')
    assert page.outer_html('#content') == '<div id="content">Welcome to Example Domain</div>'
    

这些只是 Playwright 中可用断言方法的几个示例。通过使用这些方法,您可以编写功能强大且灵活的测试来验证您的 Web 应用程序的功能。

猜你喜欢

转载自blog.csdn.net/u013589130/article/details/129329132