Mikael Mikaelian
Mikael Mikaelian

Reputation: 17

Python, Selenium: how to refresh page until element is present

while True:
    try:
        browser.find_element_by_xpath('//*[@id="layoutPage"]/div[1]/div/div/div[3]/div[4]/div[2]/div/section/div[1]/div/button/div')
        break
    except NoSuchElementException:
        browser.refresh()

Why do I still get selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="layoutPage"]/div[1]/div/div/div[1]/div/div[1]/button[2]"} eroor? I have imported the NoSuchElementException from selenium.common.exceptions.

Upvotes: 0

Views: 6505

Answers (2)

Indian Gamex
Indian Gamex

Reputation: 21

you can use time.sleep() command after refreshing see if it works,

i guess it will because it instantly analyses the page after refreshing, because of which the page doesn't get time to fully load itself and throws error to you as it doesn't get the desired thing which it is searching for !

hope it helps !!!

while True:
    element = browser.find_elements_by_xpath('//*[@id="layoutPage"]/div[1]/div/div/div[3]/div[4]/div[2]/div/section/div[1]/div/button/div')
    if element != None:
        print("got it !")
        break
    else:
        browser.refresh()
        time.sleep(2)
        continue      

or

for i in range(1):
    while True:
    element = browser.find_elements_by_xpath('//*[@id="layoutPage"]/div[1]/div/div/div[3]/div[4]/div[2]/div/section/div[1]/div/button/div')
    if element != None:
        print("got it !")
        break
    else:
        browser.refresh()
        time.sleep(2)
        continue 

Upvotes: 2

Prophet
Prophet

Reputation: 33381

Try

while True:
    try:
        browser.find_element_by_xpath('//*[@id="layoutPage"]/div[1]/div/div/div[3]/div[4]/div[2]/div/section/div[1]/div/button/div')
        break
    except:
        browser.refresh

or maybe this:

while True:
    if(browser.find_elements_by_xpath('//*[@id="layoutPage"]/div[1]/div/div/div[3]/div[4]/div[2]/div/section/div[1]/div/button/div')):
        break
    else:
        browser.refresh

Pay attention, I'm using find_elements in the second code. It returns list. In case the list is non-empty it should enter the if else it will go into else and refresh the page

Upvotes: 4

Related Questions