Home > Mobile >  Using Selenium webdriver with a For Loop
Using Selenium webdriver with a For Loop

Time:09-28

I am attempting to write a for loop to select product UPC's on a website. Essentially I have a list of UPC's in an Excel file that I want to loop through to EITHER: (1) Find the item through the search bar and select it OR (2) Item is not found and I want to add it to a list of Not Found UPCs. This is where I am at so far. I am unsure if I should use an IF ELSE statement or something else. I would really appreciate any thoughts or guidance.

for upc in upc_list:
    driver.find_element_by_xpath('xpath for search bar').clear()
    driver.find_element_by_xpath('xpath for search bar').send_keys(upc)
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="' upc '"]'))).click()

CodePudding user response:

if the element is not found an exception will be thrown and you have to catch it with a try except

upc_list=[]
not_found_list=[]
for upc in upc_list:
    driver.find_element_by_xpath('xpath for search bar').clear()
    driver.find_element_by_xpath('xpath for search bar').send_keys(upc)
    try:
        WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="' upc '"]'))).click()
    except:
        print('no results for ' upc)
        not_found_list.append(upc)
        continue
    print('results for ' upc)
    # utc is found
    # do what ever you want with it
  • Related