Reputation: 1782
I need to find a specific element in my webpage. The element may be in the page or not.
This code is giving me error if the element is not visible:
error_text = self.page.wait_for_selector(
self.ERROR_MESSAGE, timeout=7000).inner_text()
How can I look for the element using timeout, and get a bool telling me if the element is found or not?
Upvotes: 4
Views: 8046
Reputation: 9616
I don't like it, wish there was something convenient, but I am using like this - showing Javascript code
async function isPresent(locator: Locator): Promise<boolean> {
let isPresent = false;
try {
await locator.waitFor({ state: 'attached', timeout: 20 });
isPresent = true;
} catch(err) {}
return isPresent;
}
Upvotes: 1
Reputation: 11
You can use page.wait_for_selector(selector, timeout)
with try except block to check the web element is present or not if that element takes some time to load.
try:
page.wait_for_selector(selector, timeout)
print('element found')
except:
print('element not found')
Upvotes: 1
Reputation: 18650
You have to use the page.is_visible(selector, **kwargs)
for this as this returns a boolean value. Playwright Docs,
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")
You can also use expect
assertion if you directly want to assert the presence of the element and fail the tests if the condition is not met.
expect(page.locator("selector")).to_have_count(1, timeout=7000)
Upvotes: 7