Home > Blockchain >  Selenium not entering try block after refreshing the web page
Selenium not entering try block after refreshing the web page

Time:04-12

I have written a piece of code wherein I am using a try except block to check for an event. In the try block, if the specified button is found, the code should wait for 10 seconds and then refresh the page. If it's not found, it should refresh the page in 3 seconds.

But what's happening over here is that after executing the code, let's say the code entered the except block for the first 3 times because the element that we were looking for was not there. But when the element occurs for the first time in the 4th run, the code still goes to the except block .

Can someone help me figure out where my logic might be going wrong?

while True:
    browser.refresh()
    time.sleep(7)
    try:
        Check = browser.find_element_by_class_name("btn btn-sm btn-default")
        time.sleep(10)
        browser.refresh()
    except NoSuchElementException:
        time.sleep(3)
        browser.refresh()

Thank you so much for the help.

CodePudding user response:

You used browser.find_element_by_class_name but provided a css selector.
You should search for the element using find_element with a By object, since find_element_by_class_name is deprecated.

check = browser.find_element(By.CSS_SELECTOR, 'btn btn-sm btn-default')

CodePudding user response:

I suspect the issue could be due to time.sleep(7). If the element btn btn-sm btn-default takes more than 7 sec to load, then the code would enter the try, but jumps to except since the element is not found yet. I would recommend to try WebdriverWati instead of time.sleep(). Also, it is not clear on why you are waiting for 10 sec when the element is found. So for now, I have reduced it to 3 sec, but you may alter it as you like; and, I have removed the sleep in except block, and placed a print statement instead. Below is the code:

while True:
    browser.refresh()
    # time.sleep(7)
    try:
        Check = WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, "btn btn-sm btn-default")))
        print(Check)
        time.sleep(3) # retaining this line just for you to observe the action.
        browser.refresh()
    except NoSuchElementException as e:
       # time.sleep(3)
        print(f"no such element found:  {e}")
        browser.refresh()

Imports required:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

You may alternately try to locate with CSS_SELECTOR as suggested by @Kfir Doron

However, if both the solutions fail to work, then you may have to look at a more precise element itself instead of the class btn btn-sm btn-default

  • Related