0
votes

I'm putting errors in Try and Except, but I'm having trouble with 2 types of errors. I'll give you an example of what I need. This except with Valure Error works fine, because I know the error is called ValueError, so:

#ONLY EXAMPLE
except ValueError:
    return "FAILED"

EXCEPT ERROR N.1 The question I ask you is: how should I write for the following error? It consists of the wrong name of an html class when scraping. I wrote selenium.common.exceptions.NoSuchElementException, but the error search does not work (the script does not open at all)

except selenium.common.exceptions.NoSuchElementException:
    return "FAILED"

EXCEPT ERROR N.2 Same thing for the database insert error. I want to make sure that if 0 records are saved in the database then I have an error. I tried to write like this, but it's not good:

except  records_added_Results = records_added_Results = + 0:
    return "FAILED"

I wrote this because I have this code for the insertion in the database. It works correctly, I am writing it just to make you understand:

    con = sqlite3.connect('/home/mypc/Scrivania/folder/Database.db')
    cursor = con.cursor()
    records_added_Results = 0

    Values = ((SerieA_text,), (SerieB_text,)
    sqlite_insert_query = 'INSERT INTO ARCHIVIO_Campionati (Nome_Campionato) VALUES (?);'
    count = cursor.executemany(sqlite_insert_query, Values) 
    con.commit()

    print("Record inserted successfully ", cursor.rowcount)
    records_added_Results = records_added_Results + 1
    cursor.close()

How should I write? Thank you

1
What have you imported? If you have from selenium.common.exceptions import NoSuchElementException you can simply use except NoSuchElementException - not_speshal
@not_speshal I imported two things: from selenium import webdriver and then from selenium.webdriver.firefox.firefox_profile import FirefoxProfile. So how should I write? Thank you - Frederick Man
Which part of your code causes the NoSuchElementException? - not_speshal
@not_speshal When with driver.get ("link"), I search for a class in a site to scrape it with SerieC_B = driver.find_element_by_class_name ("teamHeader__name"). I want to make sure that: if the class has a different name from the one I wrote (for example changed by the site over time/years), then I get the error selenium.common.exceptions.NoSuchElementException - Frederick Man

1 Answers

1
votes

Import the exception before you try to catch it. Add this line to your imports:

from selenium.common.exceptions import NoSuchElementException

Then you can simply do:

try:
    #code that could raise the NoSuchElementException
except NoSuchElementException:
    #exception handling

For the other exception, it looks like you're trying to raise an exception. Consider something like this:

if records_added_Results == 0:
    raise ValueError("error message")