0
votes

I have written a function where a user inputs the TYPE of strategy to use (i.e. By.XPATH, By.ID, By.NAME, ect..) and the ADDRESS of where that object should exist and the function will select the Selenium method to use, locate the object, and scroll it into view.

    view_object(driver, type, address):
        strategy = {
            "css_selector": driver.find_element_by_css_selector,
            "id":           driver.find_element_by_id,
            "link_text":    driver.find_element_by_link_text,
            "name":         driver.find_element_by_name,
            "xpath":        driver.find_element_by_xpath
            }
        lhsType, rhsType = type.split(".", 1)
        find_element = strategy.get(rhsType.lower())

        obj = find_element(address)
        driver.execute_script("return arguments[0].scrollIntoView();", obj)

The reason I created this function had to do with tests I had that failed to run on Internet Explorer (IE) that weren't failing on Firefox or Chrome. After some investigation, I concluded the failures would occur anytime I was trying to test an object that needed to first be scrolled to and made visible on the page.

Anyhow, back to the issue. I have a situation where the code fails at the "obj = find_element(element)" line because the object takes about 30-45 seconds to load.

To resolve this issue, I believe I need to create a class in such a way that this line of code can use the Selenium WebDriverWait(driver, time) method and then it will have an allotted amount of time to attempt this operation before failing. How would I go about this?

1

1 Answers

0
votes

You can use implicitly_wait as well. In this case you don't have to change your function. The drawback is that the driver will wait the specified amount of time each time when locating an element, which is not always desired.

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(60)


Or you can be specific as you asked for

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def view_object(driver, type, address):
    strategy = {
        "css_selector": By.CSS_SELECTOR
        "id":           By.ID,
        "link_text":    By.LINK_TEXT,
        "name":         By.NAME,
        "xpath":        By.XPATH
        }
    lhsType, rhsType = type.split(".", 1)
    find_element = strategy.get(rhsType.lower())

    wait = WebDriverWait(driver, 60)
    obj = wait.until(EC.presence_of_element_located((find_element, address)))
    driver.execute_script("return arguments[0].scrollIntoView();", obj)