Reputation: 15
Condition Statement - Try, Except, Else -
I am using Selenium/Python to automate some tasks for downloading and uploading files.
Is there a way to have Selenium/Python recognize if a page is loaded as a 404? ie my "Try" attempt below.
My goal is to have the script close out the tab if it loads as a 404 error and loop until a downloadable file is found. The file is a PDF.
I've attempted using XPath to search for specific text such as:
'Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.' - but am not certain as to the proper coding needed. I'm new to this so thanks for bearing with me.
Below is the bottom portion of the script and it is in a loop as well - (the 'icon' is the download button which shows on the downloadable page, but not on the 404 page)
try:
Download = driver.find_element_by_id('icon')
if Download == driver.find_element_by_id('icon'):
raise Exception
except Exception:
pyautogui.time.sleep(2)
pyautogui.hotkey('ctrl','s')
pyautogui.time.sleep(2)
pyautogui.hotkey('enter')
pyautogui.time.sleep(2)
pyautogui.hotkey('ctrl','w')
pyautogui.click(771, 374, duration=0.55)
pyautogui.click(867, 276, duration=0.55)
else:
pyautogui.time.sleep(2)
pyautogui.hotkey('ctrl','w')
pyautogui.time.sleep(2)
pyautogui.doubleClick(79, 136, duration=0.55)
pyautogui.time.sleep(15)
pyautogui.click(642, 442, duration=0.55)
pyautogui.time.sleep(2)
pyautogui.hotkey('ctrl','s')
pyautogui.time.sleep(2)
pyautogui.hotkey('enter')
pyautogui.time.sleep(2)
pyautogui.hotkey('ctrl','w')
pyautogui.click(771, 374, duration=0.55)
pyautogui.click(867, 276, duration=0.55)
The code above doesn't close out the 404 webpage if it loads. Rather the script saves the webpage 404 instead of attempting the "Else" portion of the script.
Thanks for the help! (If I can give an upvote I will.)
Upvotes: 0
Views: 3485
Reputation: 717
Webdriver wont catch the http404, this is not implemented in the API and it wont be, check their issue tracker. You could use just python for that, maybe this will help.
Upvotes: 1