Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading