Answer the question
In order to leave comments, you need to log in
How to make While work correctly if the object is not visible on the page (Python Selenium)?
Hello everyone, I wrote a code for Splinter Python:
Will execute browser.find_by_css('.u-decoration-none.next.pagination-links_anchor').click() - scroll the page until the element is found by XPATH, when it finds browser.find_by_xpath (XPATH).first.click() - will click on it.
with Browser('chrome', options=None, user_agent=None) as browser:
while (browser.is_element_present_by_xpath(XPATH) == False):
browser.find_by_css('.u-decoration-none.next.pagination-links_anchor').click()
sleep(4)
else:
browser.find_by_xpath(XPATH).first.click()
sleep(5)
browser.quit()
XPATH = '//a[@href="/biz/college-pro"]'
account = driver.find_element_by_xpath(XPATH)
while (account.is_displayed() == False):
driver.find_element_by_css_selector('.u-decoration-none.next.pagination-links_anchor').click()
sleep(4)
else:
account.click()
sleep(5)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href="/biz/college-pro"]"}
Answer the question
In order to leave comments, you need to log in
driver.implicitly_wait(5) # говорим, чтобы драйвер не унывал, если не найдёт элемент сразу, и пробовал подождать, в течение 5 секунд
while True:
try:
element = driver.find_element_by_xpath(XPATH)
except NoSuchElementException:
driver.find_element_by_css_selector('.u-decoration-none.next.pagination-links_anchor').click()
else:
element.click()
break
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question