0

I'm trying to decide on whether to use if and else or try and exception to handle NoSuchElementException.

I tried using below but it's not working. The NoSuchElementException error appears and the program stops there and doesn't continue to the else statement.

if len(driver.find_element(By.XPATH, "//*[@id='order.list_order_list_order_list[1].ref_doc_no']/span"))>0:
    driver.find_element(By.XPATH, "//*[@id='order.list_order_list_order_list[1].ref_doc_no']/span").click()
    driver.implicitly_wait(10)
    driver.find_element(By.XPATH, "//td[7]/a/span").click()
    
else:
    driver.find_element(By.XPATH, "//*[@id='breadcrumb_susBreadCrumb']/a[2]/span").click()
    enter_po_search("3020331278")

I used below and it works.

try:
    driver.find_element(By.XPATH, "//*[@id='order.list_order_list_order_list[1].ref_doc_no']/span").click()
    driver.implicitly_wait(10)
    driver.find_element(By.XPATH, "//td[7]/a/span").click()
    enter_po_search("3020331278")

except NoSuchElementException:
    driver.find_element(By.XPATH, "//*[@id='breadcrumb_susBreadCrumb']/a[2]/span").click()
    enter_po_search("3020331278")

Am I doing this right? Is there a better way to code this?

Nico
  • 15
  • 5

1 Answers1

2

The reason that you are still getting error in the first snippet is that you are using find_element instread of find_elements

so replacing

if len(driver.find_element(By.XPATH, "//*[@id='order.list_order_list_order_list[1].ref_doc_no']/span"))>0:

into

if len(driver.find_elements(By.XPATH, "//*[@id='order.list_order_list_order_list[1].ref_doc_no']/span"))>0:

will work.

For the style of coding, in Python, it is very common and acceptable to use try-except in your logic flow, more on that here. So either using if-else, or using try-except is ok.

kennysliding
  • 2,783
  • 1
  • 10
  • 31
  • Thanks! No wonder the `if` statement didn't work. Thanks for the reading material too, I appreciate it. – Nico Oct 21 '20 at 14:31