Check if web element exists

Hi,

I have experience with other RPA platforms and usually, they have a keyword that checks if an element exists and returns a boolean, allowing you to configure parameters like a timeout. I know it is possible to do it with a Run Keyword And Return Status combined with a Get Element (Playwright), just like this:

    ${previous_timeout}=    Set Browser Timeout    0.1 s
    ${next_page_exists}=    Run Keyword And Return Status    Get Element    xpath=//a[text()='Next >']
    Set Browser Timeout    ${previous_timeout}

I am considering here that the page is fully loaded, that is why I’m trying to do an instant verification if the element exists.

My question is: Is this the recommended way to deal with this kind of situation in Robocorp?

Hello @Vini,

There is a better and good way to verify whether a web-element is present or not.

Does Page Contain Element    <xpath_for_element>

For more information, checkout Does Page Contain Element

For playwright element waits are built in to keywords. There is couple ways to achieve your goal, for example Wait Until Network Is Idle , Get Element States , Wait For Navigation. Get Element States actually does what you have implemented. My recommended way is to check library documentation and try to adjust to the way it works :sunny:
And with RPA I’ve used rule: If its stupid but it works, it’s not stupid

Yeah, that works great for Selenium, but I am exploring a little bit with Playwright in this case.

Thanks, @linkraivo. I’m already waiting for the page to load, so I was more curious to know if there is a Does Page Contain Element equivalent for Playwright.

Following your tip on the Get Element States I was able to come up with this solution:

${element_exists}=    Get Element States    ${selector}    then    bool(value & attached)

It does an instantaneous check if some element exists and then returns a boolean.

Not my case, but you might also want to evaluate if it is visible or any other available state.

Ended up improving it a bit to not throw an error if multiple elements are found:

${old_mode}=    Set Strict Mode    False
${element_exists}=    Get Element States    ${selector}    then    bool(value & attached)
Set Strict Mode    ${old_mode}
1 Like