代码之家  ›  专栏  ›  技术社区  ›  Josh Correia sgargan

Python Playwright-如何检查元素是否没有href?

  •  1
  • Josh Correia sgargan  · 技术社区  · 1 年前

    作为自动测试的一部分,我试图验证href是否已正确地从页面上的元素中删除。

    from playwright.sync_api import Page, expect
    
    def test_reset_button(page: Page):
        page.goto("https://www.example.com")
        page.locator("#reset").click()
        expect(page.locator("#download")).not_to_have_attribute("href", value="")
    

    在我上面的示例代码中,它最终测试元素的href属性不等于 value="" ,这意味着如果 value="nonsense" 这个测试会通过的。

    基于 not_to_have_attribute 文档似乎必须向它传递一个值,以测试它是否没有特定的值。我想测试元素上是否根本不存在“href”属性。

    我该如何测试?

    2 回复  |  直到 1 年前
        1
  •  1
  •   ggorlen Hoàng Huy Khánh    1 年前

    您可以使用正则表达式 .| 测试属性的存在性,包括两者 href="something" href="" 这个 "" case由交替管道右侧的空字符串处理。您可以将模式读取为“要么匹配,要么不匹配”(即所有可能的字符串)。

    import re
    from playwright.sync_api import expect, Page, sync_playwright  # 1.37.0
    
    
    sample_html = """<!DOCTYPE html>
    <button id="reset">reset</button>
    <a id="download" href="nonsense">download</a>
    <script>
    document.querySelector("#reset").addEventListener("click", () => {
      document.querySelector("#download").removeAttribute("href");
    });
    </script>"""
    
    
    def test_reset_button(page: Page):
        page.set_content(sample_html)
        dl = page.locator("#download")
    
        # assert that there is an href present initially
        expect(dl).to_have_attribute("href", re.compile(r".|"))
    
        # trigger an event to remove the href
        page.locator("#reset").click()
    
        # assert that there is no longer an href present after the click
        expect(dl).not_to_have_attribute("href", re.compile(r".|"))
    
    
    
    def main():
        with sync_playwright() as p:
            browser = p.chromium.launch()
            test_reset_button(browser.new_page())
            browser.close()
    
    
    if __name__ == "__main__":
        main()
    

    re.compile 很重要。使用 ".|" "/.|/" 会将其视为测试相等性的文字字符串。

    另一种方法是查询元素,将确切的href存储在变量中,单击按钮删除该href,然后断言之前保存的确切href不再存在。如果href更改为其他内容,这将给出一个假阳性,但这似乎值得一提,因为它在某些情况下可能有用。

        2
  •  0
  •   Serge    1 年前

    value参数可以是Pattern,也就是正则表达式 .* (代表任何字符序列,即任何东西),或者,如果你喜欢, .? (任意符号或无符号)应同时捕获“无意义”和空值。

    推荐文章