Search code examples
pythonselenium-webdriverxpathfindelement

Is there a way to structure an if statement so that it can identify if an XPATH exists in python selenium?


I am currently playing around with Selenium trying to learn it by doing and have encountered this issue; occasionally a button on the website appears with a different XPATH, so I wanted to try and create a workaround. This is what I am trying to use:

if bool(wd.find_element_by_xpath('//*[@id="basketPageApp"]/div/div[2]/div/div/div[1]/div/div[2]/a')) == TRUE:
    button = wd.find_element_by_xpath('//*[@id="basketPageApp"]/div/div[2]/div/div/div[1]/div/div[2]/a')
else:
    button = wd.find_element_by_xpath('//*[@id="guestCheckout"]/div/div/div[2]/section/div[2]/div[1]/div')

I'm sure I can't use an if statement in this manner but I hope this gets the idea of what I am trying to achieve across.


Solution

  • Selenium will throw an exception in case find_element method could not find element matching the passed locator.
    It will not return you a Boolean True or False.
    What can you do here is to use find_elements_by_xpath instead of find_element_by_xpath since find_elements_by_xpath will return you a list of found matches. So, in case there was a match you will get a non-empty list interpreted by Python as a Boolean True while in case of no match found it will return an empty list interpreted by Python as a Boolean False. Also, this will never throw exception.
    So your code could be something like:

    if wd.find_elements_by_xpath('//*[@id="basketPageApp"]/div/div[2]/div/div/div[1]/div/div[2]/a'):
        button = wd.find_element_by_xpath('//*[@id="basketPageApp"]/div/div[2]/div/div/div[1]/div/div[2]/a')
    else:
        button = wd.find_element_by_xpath('//*[@id="guestCheckout"]/div/div/div[2]/section/div[2]/div[1]/div')