'How can I refresh the Python Selenium until I can click xpath?

How can I refresh the Python Selenium until I can click xpath?

xpath_click = '//*[@id="wrapcalendar"]/div[2]/div/div[1]/table/tbody/tr[5]/td[5]'

while True: 

 element = driver.find_element_by_xpath(xpath_click)
 if element.text == 'xpath_click':
    element.click()
    break 
 else :
    driver.refresh()
    driver.implicitly_wait(1)


Solution 1:[1]

You were fairly close, few things:

  1. You should know the expected string in advance, based on that we will have an if condition, see below.

  2. wrap the risky code inside try and except block.

  3. You should wait (hardcoded) for at least 2 seconds so that page refresh is done successfully.

Code:

while True:
    try:
        element = driver.find_element(By.XPATH, xpath_click).text
        if element == "your expected string here":
            element.click()
            print("Clicked on the element so break from infinite loop.")
            break
        else:
            driver.refresh()
            time.sleep(2)
    except:
        print("Something went wrong")
        break
        pass

Solution 2:[2]

I am not sure why are you putting this inside an if loop, have you tried waiting for an element? Example suited for your scenario:

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.xpath, '//*[@id="wrapcalendar"]/div[2]/div/div[1]/table/tbody/tr[5]/td[5]')))
element.click()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cruisepandey
Solution 2 Funky Monkey