Home > database >  python try statement or if statement
python try statement or if statement

Time:02-25

Hello everyone I have my code almost done but I'm trying to add in some sort of check to avoid errors. But I'm not really understanding what statement would be better to use to test the code. I know there are a few options of either using a loop, if-statement, or try. But here is the code in regards to doing captcha. I need it to run the first set of code which if the captcha doesn't pop up I continue on. But if the captcha does pop up solve it then continue on.

Here is the first set of code to run first. To test and see if a captcha doesn't appear. Some times captcha doesnt appear and if I run the whole set of code I get an error because we are expecting captcha to pop up.

search_box = driver.find_element(By.ID,"caseCriteria_SearchCriteria")
    search_box.send_keys("testing")
    #Code to click captcha
    WebDriverWait(driver, 15).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name^='a-'][src^='https://www.google.com/recaptcha/api2/anchor?']")))
    WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, "//span[@id='recaptcha-anchor']"))).click()
    driver.switch_to.default_content() #necessary to switch out of iframe element for submit button
    delay() 
    submit_box = driver.find_element_by_id("btnSSSubmit").click()

If captcha doesnt appear run this code and finish.

soup = BeautifulSoup(driver.page_source,'html.parser')  
df = pd.read_html(str(soup))[0]
df.dropna(inplace=True)
df= df.droplevel(level=[0, 1], axis=1).query("`Case Number` != 'Case Number'")
print (df)

Or if the captcha does appear to solve it which would be this code below. Then run the above code and finish.

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='recaptcha challenge expires in two minutes']")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#recaptcha-audio-button"))).click()
delay()

#get the mp3 audio file
src = driver.find_element(By.ID,"audio-source").get_attribute("src")
print("[INFO] Audio src: %s"%src)
   #create path to mp3 and wav file
path_to_mp3 = os.path.normpath(os.path.join(os.getcwd(), "sample.mp3"))
path_to_wav = os.path.normpath(os.path.join(os.getcwd(), "sample1.wav"))

I would really appreciate any help please as I'm not sure the right statement to use.

CodePudding user response:

try should be used when something would return an error and would otherwise cause your program to stop/crash. An example of this would be:

try:
    import pandas
except:
    print("Unable to import pandas.  Module not installed")

In this example your program will attempt to import the pandas module. If this fails it will then print out a line of text and continue running.

if statements are used to decided when to do something or not based on the returned logic. The key difference is that logic IS returned and not an error.

if x > 10:
   print("This is a large number")
else: 
   print("This is a small number")

With this example, if 'x' did not exist it would produce an error, no more code will be executed, and the program will crash. The main difference between IF and TRY is whether logic is returned as true/false or is something just plains fails.

With your specific example it is important to know if the captcha appearing or not will break your code. Does the logic boil down to captcha = false or does captcha not exist at all and logic fails entirely?

CodePudding user response:

Q: How do you define sometimes captcha doesn't appear (1%, 20%, 50%, ...)?

A: Maybe 5% of the time captcha doesn't appear.

In this case, I prefer to use Exception handling: do stuff and if something goes wrong, fix it

try:
  # > 95% of the time the code below works when the captcha appears
except SomeException:
  # < 5% of the time the code is called when the captcha doesn't appear

IMHO, you have not really 2 different codes: you have one and a fallback solution, it's really different than:

if x % 2:
    ...
else:
    ...
  • Related