You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Playwright验证元素不存在href属性?

验证元素完全不存在href属性的Playwright测试方法

要验证元素完全没有href属性,你需要调整测试逻辑,以下是两种可行的实现方式:

方法一:使用not_to_have_attribute(仅传属性名)

修正后的测试代码如下:

from playwright.sync_api import Page, expect

def test_reset_button(page: Page):
    page.goto("https://www.example.com")
    page.locator("#reset").click()
    # 验证元素完全不存在href属性
    expect(page.locator("#download")).not_to_have_attribute("href")

当仅传入属性名称时,not_to_have_attribute会检查目标元素完全不包含该属性,而非验证属性值不等于某个特定值,这正好匹配你需要的场景。

方法二:直接断言属性返回值为None

你也可以通过get_attribute方法获取属性值,直接断言其为None(元素不存在该属性时,get_attribute会返回None):

from playwright.sync_api import Page

def test_reset_button(page: Page):
    page.goto("https://www.example.com")
    page.locator("#reset").click()
    download_element = page.locator("#download")
    # 断言href属性不存在
    assert download_element.get_attribute("href") is None

内容的提问来源于stack exchange,提问作者Josh Correia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 17:54:54