As you can see in the image, I have 2 solutions (solution 1 is for a flight and solution 2 is for a hotel)
I want to iterate over each solution using XPATH. I am successful in that. I want to check the image returned on iteration.
My code is somewhat like this:
if select_solution.size != 0:
print(str(i) " solution selected")
if '/assets/review/images/nodes/icon-plane.png' in driver.find_element(By.XPATH, config.RT_flightImage_check_Xpath.format(i)).get_attribute("src"):
result['Solution ' str(i)] = {}
print("Solution is for Flight")
print("**********************")
returned_solution = 'Flight'
result['Solution ' str(i)]['Returned Solution'] = returned_solution
elif 'assets/review/images/nodes/icon-hotel.png' in driver.find_element(By.XPATH, config.RT_HotelImage_check_Xpath.format(i)).get_attribute("src"):
result['Solution ' str(i)] = {}
print("Solution is for Hotel")
print("**********************")
returned_solution = 'Hotel'
result['Solution ' str(i)]['Returned Solution'] = returned_solution
Result:
Total number of Solutions found: 2
1 solution selected
Solution is for Flight
**********************
--------
2 solution selected
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//hgb-content-view[1]/div[1]/div[1]/div[2]/div[1]/hgb-flight-content-view[1]/div[1]/div[2]/div[1]/img[1]"}
(Session info: chrome=103.0.5060.134)
The issue that i am facing is that when it iterates the 1st time, it finds the flight and does the necessary operation, but during the second iteration it fails because it does not find the flight (No such element
exception).
How do I make sure that it goes to the elif
and not exit cause the flight xpath is not found in the selected iteration?
CodePudding user response:
try:
elem=driver.find_element(By.XPATH, config.RT_flightImage_check_Xpath.format(i))
except Exception as e:
print(str(e))
elem=[]
pass
Try except and catch the error and display it. Then do it for the other one.
if len(elem)!=0 and '/assets/review/images/nodes/icon-plane.png' in elem.get_attribute("src"):
#your code
elif len(elem2)!=0 and 'assets/review/images/nodes/icon-hotel.png' in elem2.get_attribute("src"):
#your code
CodePudding user response:
This actually worked. Had to tweak it a little instead of find_element, I used find_elements
try:
flight_element=driver.find_elements(By.XPATH, config.RT_flightImage_check_Xpath.format(i))
except Exception as e:
print(str(e)) elem=[] pass
if len(flight_element) != 0 and '/assets/agent/icons/transaction/plane.svg' in driver.find_element(By.XPATH, config.AA_flight_icon_Xpath.format(i)).get_attribute("svg"):
and this way, in second iteration i was able to find the hotel and get the desired result