I am doing a program in which a user logins to his account (100% done) and after that it goes to a site (www.site.com (not this one tho)) and searches for an element. The problem: Element is not always there, it pops out RANDOMLY so I wanted to do a program where when it doesn't get a drop (candy) it goes to another tab.

I have tried many stuff, changing loops, adding/removing stuff from try,except etc...

```py
for i in range(10000):
    while True:
        print("Starting!")
        try:
            element = browser.find_element_by_xpath('//*[@id="redeem-candy-voucher"]')#.click()
        except NoSuchElementException:
            pass
        browser.execute_script("arguments[0].click();", element)

        print("Clicked Candy! Skullbux Gained!")

        time.sleep(3)

        browser.execute_script("window.open('');")
        browser.switch_to.window(browser.window_handles[1])
        browser.get("https://www.brickplanet.com/events/trick-or-treat")

        time.sleep(3)

        try:
            element = browser.find_element_by_xpath('//*[@id="redeem-candy-voucher"]')#.click()
        except NoSuchElementException:
            pass
        browser.execute_script("arguments[0].click();", element)

        print("Clicked Candy! 0.25 Gained!")
        #browser.close()
        time.sleep(5)

```

There are 2 possible errors.
One where it finds element, then it refreshes a page and then gets an error:

```
DevTools listening on ws://127.0.0.1:52479/devtools/browser/a2cfa4b3-e538-49fb-872c-114db52513ce
Starting!
Clicked Candy! Skullbux Gained!
Traceback (most recent call last):
  File "C:\Users\DOMA\Desktop\bp hack.py", line 54, in <module>
    browser.execute_script("arguments[0].click();", element)
  File "C:\Users\DOMA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 636, in execute_script
    'args': converted_args})['value']
  File "C:\Users\DOMA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\DOMA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=77.0.3865.90)

```

And when it doesn't find any element at all:

```
DevTools listening on ws://127.0.0.1:52432/devtools/browser/9250b0fb-2742-4a8b-9043-b7cdbec1f8e3
Starting!
Traceback (most recent call last):
  File "C:\Users\DOMA\Desktop\bp hack.py", line 38, in <module>
    browser.execute_script("arguments[0].click();", element)
NameError: name 'element' is not defined

Process returned 1 (0x1)        execution time : 20.796 s
Press any key to continue . . .

```