如何使用 Playwright 和超时参数检查元素是否存在

Tal*_*gel 2 python playwright playwright-python

我需要在我的网页中找到特定元素。该元素可能位于页面中,也可能不在页面中。

如果元素不可见,此代码会给我错误:

error_text = self.page.wait_for_selector(
            self.ERROR_MESSAGE, timeout=7000).inner_text()
Run Code Online (Sandbox Code Playgroud)

如何使用超时查找元素,并获得一个布尔值告诉我是否找到该元素?

Ala*_*Das 6

您必须page.is_visible(selector, **kwargs)为此使用,因为它返回一个布尔值。剧作家文档

bool = page.is_visible(selector, timeout=7000)
print(bool)

#OR

if page.is_visible(selector, timeout=7000):
    print("Element Found")
else:
    print("Element not Found")
Run Code Online (Sandbox Code Playgroud)

expect如果您想直接断言元素的存在并在不满足条件时使测试失败,也可以使用断言。

expect(page.locator("selector")).to_have_count(1, timeout=7000)
Run Code Online (Sandbox Code Playgroud)