Python try-except doesn't work as intended - python

I have the following code and for some reason it doesn't quit the browser when the two elif statements are triggered OR go to the except part of the code.
The goal is to return False in every case where the "Solved" attribute is not found. I have tried removing the elif parts so that it would go to except part in all of the other cases but it still doesn't work.
while True:
try:
sleep(10)
status = browser.find_element(By.CLASS_NAME, 'status')
if status.get_attribute("innerHTML") == "Solved":
break
elif status.get_attribute("innerHTML") == "Unknown error, watch console":
browser.quit()
print("Unknown error - programm ootab 3 minutit...\n")
sleep(180)
return False
elif status.get_attribute("innerHTML") == "Outdated, should be solved again":
browser.quit()
print("Captcha outdated - programm ootab 3 minutit...\n")
sleep(180)
return False
except:
print('Captcha fked up for some reason \n')
browser.quit()
return False

Related

Seeking assistacne with an on online Python course exercise please

I have been doing an online Python course and the final exercise was to check a list of email addresses for invalid addresses.
The code is
def has_invalid_characters(string):
valid = "abcdefghijklmnopqrstuvwxyz0123456789."
# your code here
for i in string:
if i not in valid:
return True
else:
return False
def is_valid(email):
if email.count("#") != 1:
return False
prefix, domain = email.split("#")
if len(prefix) == 0:
return False
if domain.count(".") != 1:
return False
domain_name, extension = domain.split(".")
if len(domain_name) == 0 or len(extension) == 0:
return False
if has_invalid_characters(prefix) == True:
return False
if has_invalid_characters(domain) == True:
return False
else:
return True
emails = [
"test#example.com",
"valid#gmail.com",
"invalid#gmail",
"invalid",
"not an email",
"invalid#email",
"!#/",
"test##example.com",
"test#.com",
"test#site.",
"#example.com",
"an.example#test",
"te#st#example.com",
"test#exam!ple.com"
]
for i in emails:
is_valid(i)
if i == True:
print(i + " is valid")
else:
print(i + " is invalid")
When I run this I am told that the first two email addresses, which should be reported as valid, are invalid, but I cannot figure out why. I have gone over it a few times and cannot see an error in the logic. I have also run it on my laptop and I get the same result.
In the course this code was written in steps and with the last step to change the for loop from simply printing the email addresses to validating them and everything until I modified the for was marked as correct.
I would be grateful if someone could point out the issue with this code to me.
I found the issue. My call to the is_valid() function was not correct.
it should be
for i in emails:
result = is_valid(i)
if result == True:
.....
Sorry for troubling you with this.

How to try-except block exit when try is working

The code I have works. The last for loop gets reached and choice.click() gets clicked on. The question I have is why the except block gets executed even though the:
if choice.text == call_resource:
choice.click()
break
piece of the code is reached and the choice.click() portion works?
def select_choice(driver, resource_tag):
try:
call_resource = None
access_data = common.retrieve_tag_access_data()
for row in access_data["access_data"]:
if str(row["id"]) == resource_tag:
call_resource = row["row_tag"]["name"]
break
if call_resource is None:
access_data = common.retrieve_fixture_access_data()
for row in access_data["access_data"]:
if str(row["id"]) == resource_tag:
call_resource = row["row_tag"]["name"]
break
menu = driver.find_element_by_css_selector("ul[role='listgrid']")
choices = menu.find_elements_by_css_selector("li[role='choices']")
for choice in choices:
if choice.text == call_resource:
choice.click()
break
except:
error(logger, "unable to select choice")
pass
Because the last for loop works, shouldn't it break entirely out of the function after choice.click() without executing the except: portion of the code?
The except: portion will run only if an Exception occurred inside the try block. You should change the except: line to something like except Exception as e: and print the variable e in some way so you can discover what the problem is.
choices = menu.find_elements_by_css_selector("li[role='choices']")
for choice in choices:
if choice.text == call_resource:
choice.click()
break
Could be replaced with since your only trying to click one element with a certain text why not just try to find it. If it errors out it will go to the exception you provided.
driver.find_element(By.XPATH,f"//li[#role='choices' and contains(text(),{call_resource})]").click()
Also use to find errors use the following.
except Exception as e:
print(str(e))

Python: Looping check for internet

I'm coding a script that checks if there is any internet connection. I want it to print if there were any internet connection the last time it checked as well as if there is any currently.
def was_able_to_connect_to_internet():
try:
requests.get('https://google.com')
return True
except requests.exceptions.ConnectionError as e:
return False
was_able_to_connect_to_internet_last_time = was_able_to_connect_to_internet()
while True:
print(was_able_to_connect_to_internet_last_time, flush=True)
print(was_able_to_connect_to_internet(), flush=True)
print("-----", flush=True)
sleep(5)
I run the code and turn of the wifi when it has looped once and get the following output:
True
True
-----
True
False
-----
True
False
[Cancelled]
If it worked like I'd want it to the results would be the followning:
True
True
-----
True
False
-----
False
False
[Cancelled]
What changes should I make? All help is appreciated!
You forgot to update your was_able_to_connect_to_internet_last_time variable in the loop with the new value:
def was_able_to_connect_to_internet():
try:
requests.get('https://google.com')
return True
except requests.exceptions.ConnectionError as e:
return False
was_able_to_connect_to_internet_last_time = was_able_to_connect_to_internet()
while True:
print(was_able_to_connect_to_internet_last_time, flush=True) # Print previous status
was_able_to_connect_to_internet_last_time = was_able_to_connect_to_internet() # Update the "previous status variable with current status"
print(was_able_to_connect_to_internet_last_time, flush=True) # print current status using the previously updated variable to avoid pinging google twice
print("-----", flush=True)
sleep(5)

Python: keyboard input and loop

I am trying to build a locker with Raspberry Pi. I have a code that when entering a correct CODE = '1234' with USB keyboard it opens a servo.
Basically it works, but need to loop it somehow so, if I put wrong PIN, I am asked again to put correct.
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
e = categorize(event)
if e.keystate == e.key_down:
klawisz = e.keycode[4:]
if klawisz != "ESC":
kod = (kod + klawisz)
print(kod)
else:
break
if kod == '1234':
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
d = categorize(event)
if d.keystate == d.key_down:
klawisz = d.keycode[4:]
if klawisz == "ESC":
print('ITS OPEN')
break
else:
break
else:
print('Wrong PIN')
I tried with while loop at the beginning, but it doesn't work :(
while kod == '1234'
Hope you could you guide me to correct solution, as I am still learning Python. Thanks.
You can use while loop to repeatedly perform some operations (reading users password in your example) if some condition stays true:
def read_password():
kod = ""
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
e = categorize(event)
if e.keystate == e.key_down:
klawisz = e.keycode[4:]
if klawisz != "ESC":
kod = (kod + klawisz)
print(kod)
else:
break
return kod
while read_password() != '1234':
print('Wrong PIN, try again')
In this case you're reading password as long as it doesn't match '1234'.
Use an infinite while loop and break out of it only if the code matches.
while True:
code = input('Enter code: ')
if code == '1234':
print('Code accepted.')
break
print('Wrong code, try again.')
You can easily add an additional security feature to reduce the amount of attempts per time.
import time
attempts = 0
while True:
code = input('Enter code: ')
if code == '1234':
print('Code accepted.')
break
print('Wrong code, try again.')
attempts = attempts + 1
if attempts > 9:
print('Too many failed attempts. Please wait.')
time.sleep(600)
attempts = 0
You can run all examples above on your regular computer to test them. They use Python's built-in input function. You use the RETURN key to finalize your input instead of the ESC key in your code. You said that you read the user input with a USB keyboard, so input might even work for you with your Raspberry Pi, too.

Python: run "try" again after exception caught and worked out

Is there any way to enter try statement once again after catching the exception in the first try?
Now I'm using "while" and "if" statements and it is making the code messy.
Any ideas?
Will try to simplify it as possible, sorry that have no logic...
run = True
tryAgain = True
a=0
while run:
try:
2/a
except Exception:
if tryAgain:
tryAgain = False
a = 1
else:
run = False
You could try using a break statement in your try block:
while True:
try:
# try code
break # quit the loop if successful
except:
# error handling
Considering you are doing this in a while, then you can make use of continue to just continue back to the beginning of the while loop:
tryAgain = True
a=0
while True:
try:
2/a
break # if it worked then just break out of the loop
except Exception:
if tryAgain:
continue
else:
# whatever extra logic you nee to do here
I like using a for loop so that the trying and trying doesn't go on forever. Then the loop's else clause is a place to put the "I give up" code. Here is a general form that will support 'n' retries > 1:
a=0
num_tries = 5
for try_ in range(0,num_tries):
try:
2/a
except Exception:
print("failed, but we can try %d more time(s)" % (num_tries - try_ - 1))
if try_ == num_tries-2:
a = 1
else:
print("YESS!!! Success...")
break
else:
# if we got here, then never reached 'break' statement
print("tried and tried, but never succeeded")
prints:
failed, but we can try 4 more time(s)
failed, but we can try 3 more time(s)
failed, but we can try 2 more time(s)
failed, but we can try 1 more time(s)
YESS!!! Success...
I'm new to Python, so this may not be best practice. I returned to the try statement after triggering the exception by lumping everything into a single function, then recalling that function in the except statement.
def attempts():
while True:
try:
some code
break #breaks the loop when sucessful
except ValueError:
attempts() #recalls this function, starting back at the try statement
break
attempts()
Hope this addresses your question.

Categories