Home > Back-end >  How can I refresh the Python Selenium until I can click xpath?
How can I refresh the Python Selenium until I can click xpath?

Time:01-28

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)

CodePudding user response:

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

CodePudding user response:

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()
  •  Tags:  
  • Related