Home > database >  Continue script if search has no results selenium python
Continue script if search has no results selenium python

Time:12-31

I automated the export of some reports, based on registration numbers in list RegistrationNr.

This is the logic:

Step 1) Type the registration number into the search box (without this, the html code will not be found)

Step 2) Click on the registration number

Step 3) Go and export the report of this organization.

With my current code, if there is a number on the list which is not in the database, the program stops because it has no number to click on. How can I make it look for the next item on the list whenever this happens?

This is my code:

 for i in RegistrationNr:

      driver.find_element(By.XPATH, './/*[@title = "Searchbox"]').send_keys(i)

      driver.find_element(By.XPATH, ".//*[@title ="   ' "'  i  '"'   "]").click()

      driver.find_element(By.XPATH, './/*[@title = "Number"]').click()

Thanks!

CodePudding user response:

This can be simply achieved using try and except. Please find the code below

for i in RegistrationNr:
    driver.find_element(By.XPATH, './/*[@title = "Searchbox"]').send_keys(i)
    driver.find_element(By.XPATH, ".//*[@title ="   ' "'  i  '"'   "]").click()

    try:
        driver.find_element(By.XPATH, './/*[@title = "Number"]').click()
    except NoSuchElementException:
        print("Element is not present in the database")

CodePudding user response:

You can simply validate presence of elements with find_elements method.
In case elements found it will return a non-empty list which is seen by Python as Boolean True. Otherwise it will return an empty list which is seen by Python as a Boolean False. So your code can be something like this:

for i in RegistrationNr:

    driver.find_element(By.XPATH, './/*[@title = "Searchbox"]').send_keys(i)
    driver.find_element(By.XPATH, ".//*[@title ="   ' "'  i  '"'   "]").click()
    results = driver.find_elements(By.XPATH, './/*[@title = "Number"]')
    if(results):
        results[0].click()

CodePudding user response:

You should be using find_elements inside try-except block. Use the len function to check if find_elements has return at least 1 web element, if it has then click on it else, skip it.

Code:

for i in RegistrationNr:
    driver.find_element(By.XPATH, './/*[@title = "Searchbox"]').send_keys(i)
    driver.find_element(By.XPATH, ".//*[@title ="   ' "'  i  '"'   "]").click()
    try:
        if len(driver.find_elements(By.XPATH, ".//*[@title = 'Number']")) >0:
            driver.find_element(By.XPATH, ".//*[@title = 'Number']").click()
        else:
            # do something here when .//*[@title = 'Number'] is not available
    except:
        pass
  • Related