'Robot Framework - check if element defined by xpath exists

I'm wondering, I'd love to find or write condition to check if some element exists. If it does than I want to execute body of IF condition. If it doesn't exist than to execute body of ELSE.

Is there some condition like this or is it necessary to write by myself somehow?



Solution 1:[1]

By locating the element using xpath, I assume that you're using Sselenium2Library. In that lib there is a keyword named:

Page Should Contain Element which requires an argument, which is a selector, for example the xpath that defines your element.

The keyword failes, if the page does not contain the specified element.

For the condition, use this:

${Result}= Page Should Contain Element ${Xpath} Run Keyword Unless '${RESULT}'=='PASS' Keyword args*

You can also use an other keyword: Xpath Should Match X Times

Solution 2:[2]

I prefer using Get Matching XPath Count since the accepted answer throws error if element is not found

${count}= Get Matching XPath Count ${Xpath}
Run Keyword And Return If   ${count} > 0 Keyword args*

Solution 3:[3]

I also had the same doubt, but above answers doesn't satisfy what I wanted to

so,I used rpaframework library

*** Settings ***
Library    RPA.Browser.Selenium

*** Tasks ***
Verifying if a link is present or not
    Open Available Browser    https://www.amazon.com
    ${val}    Does Page Contain Link    //a[contains(@href,'some_text_present_in_your_link')]
    IF    ${val}== True
        Log    Link is present in the web page.
    ELSE
        Log    Link is not present in the web page.

There are many keywords present in this library to verify other things like elements, button, checkbox, image, textfield etc.

These keywords return True or False, so we can perform other steps based on variable value.

Note: Do not forget to install the rpaframework library.

pip install rpaframework

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Richard Zilahi
Solution 2 Narasimha
Solution 3 Master