Drago
Drago

Reputation: 1875

Continue when element is not found in selenium

up_key.click()
item = WebDriverWait(driver, 5).until(lambda driver: driver.find_element_by_xpath(element_xpath))
if item.text == 'awesome text':
    driver.quit()

The up_key.click() clicks on the up key image on the site, it sometimes creates a new element in AJAX which is displayed in the webpage. That new element I try to get with:
item = WebDriverWait(driver, 5).until(lambda driver: driver.find_element_by_xpath(element_xpath))

But like I said it creates sometimes a new element but not always, and the text of that element is also not always awesome text.

So if the up_key.click() would clicked again, then AJAX would either change the text of the element, or keep the same text, or remove the element. This is everytime random when up_key.click() clicks.

I want the script to continue doing up_key.click(), untill it finds awesome text then it should stop.

something like:

item = WebDriverWait(driver, 5).until(lambda driver: driver.find_elements_by_xpath(element_xpath))
while item.text != 'awesome text':
    up_key.click()
    item = WebDriverWait(driver, 5).until(lambda driver: driver.find_elements_by_xpath(element_xpath))

Upvotes: 1

Views: 536

Answers (1)

Rafael Almeida
Rafael Almeida

Reputation: 5240

To do this you have to surround the text with a try block

while True:
    try:
        up_key.click()
        item = WebDriverWait(driver, 5).until(lambda driver: driver.find_element_by_xpath(element_xpath))
        if item.text != 'awesome text':
            continue
        driver.close()
    except:
        print "Not found"

Upvotes: 1

Related Questions