Reputation: 15
I'm really new to Python and writing code, and this code doesn't seem to rerun through all the lines after it hits the exception. I want it to start again from the try function after it hits the exception. Among these 40 web elements that the code is running through, maybe like 4-5 do not have this element (id="tt_single_values_spent) and will giveNoSuchElementException. What I want is that once my code will hit the error, it will skip it and continue to gather the information. I am 100% sure the problem is with the code and not the site itself .
for i in range(40):
try:
act4 = browser.find_element_by_css_selector('dd[id="tt_single_values_spent"]').get_attribute('innerText')
time_log = re.sub('h', '', act4)
if time_log != str("Not Specified"):
total_time.append(float(time_log))
print(act4)
pyautogui.press("down", 1);time.sleep(0.5)
except NoSuchElementException:
print('Not found')
My result:
1h
45h
4h
13h
1h
31.8h
34.2h
5h
Not found
Not found
Not found
Not found
Not found
Not found
Not found
Upvotes: 0
Views: 89
Reputation: 9872
The reason your code repeatedly outputs "Not found" once it encounters a single "Not found" element, is that your code only advances elements within the try
block.
Instead, you should always advance. You can do this with a finally
block, or with code outside of the try-except block:
for i in range(40):
try:
act4 = browser.find_element_by_css_selector('dd[id="tt_single_values_spent"]').get_attribute('innerText')
time_log = re.sub('h', '', act4)
if time_log != str("Not Specified"):
total_time.append(float(time_log))
print(act4)
except NoSuchElementException:
print('Not found')
finally:
pyautogui.press("down", 1)
time.sleep(0.5)
Upvotes: 2