A
A
Adoafw2017-10-18 11:23:00
Python
Adoafw, 2017-10-18 11:23:00

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()

Everything works fine if I use Splinter.
Thanks to the is_element_present_by_xpath method, I can check if False or True is present here. How can I do this in Selenium? I tried this, but it doesn't work:
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"]"}

P / S Yes, I want to rewrite everything in Selenium because it has a .location method that gives {'y': 5380.0, 'x': 617.0} in this form the coordinates that I really need and this method is not in Splinter (((
Guys plz tell me how to solve the problem

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Adoafw, 2017-10-19
@Adoafw

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

Works

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question