Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I handle Selenium try except web error messages in python?

On my web page are two different type of errors.

The first one is:
<div class="warning" data-text="text-field-error" dir="ltr">Diese ID ist nicht verfügbar.</div>
And the second one is:

<div class="separator-notice text-notice text-margin theme-noticeerror-font" dir="ltr">Bei der Verbindung zum Server ist eine Zeitüberschreitung aufgetreten.</div>

for example if I try wrong email it doesnt have a specific value how often you can repeat. From time to time its diferent. Now the first error means that this email (in my case ID) isnt valid.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The second errors meaning is that the Server connection has failed.
Now with selenium I want to handle these two different errors something like this:

for line in lines:
    driver.find_element_by_id(input_id).send_keys(line)
    driver.find_element_by_class_name(check_available).click()
    count += 1
    time.sleep(1)
    try:
        # Check if I get error one
    except:
        # I got an error two
    else:
       pass

Ive already looked around at stack but couldnt find anything that matches my requirements.
I also have tried it with xpath by text like this:

    try:
    driver.find_element_by_xpath("//div[contains(text(), ' Diese ID ist nicht verfügbar.')]")
except:
      # It has to be error two

So now is my question:
How can i check which error i currently have and how can i work with that error. For example

if error1:
   print("error_one")
if error2:
   print("error_two")

>Solution :

You can do that even without tryexcept at all.
You can do something like this:

for line in lines:
    driver.find_element_by_id(input_id).send_keys(line)
    driver.find_element_by_class_name(check_available).click()
    count += 1
    time.sleep(1)
    first = driver.find_elements_by_xpath("//div[contains(text(), 'Diese ID ist nicht verfügbar.')]")
    second = driver.find_elements_by_xpath("//div[contains(text(), 'Bei der Verbindung zum Server ist eine Zeitüberschreitung aufgetreten')]")
    if first:
        #you have got the first notification
    if second:
        #you have got the second notification

You can also do this with the expected conditions and with tryexcept, but this approach looks to be the simplest.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading