0

I want to know if there's any method which can make me check if elements is displayed on UI faster. I've compared that if the element is shown on UI, then my code will be quickly get the result, while, if the element is not shown on UI, my code will take a long time to get the result. Why?

from selenium.common.exceptions import NoSuchElementException 
from selenium import webdriver

def is_OS_Present(Des,driver):
    td_OS_section=driver.find_element_by_id("CONTROL_OS_CTO_Options")
    try :
        td_OS_section.find_element_by_xpath("//label[contains(text(),'%s')]" %Des)
        print 'ele is displayed'
    except NoSuchElementException:
        print 'ele is not displayed'

driver=webdriver.Firefox()
driver.get("https://www-01.ibm.com/products/hardware/configurator/americas/bhui/launchNI.wss")
driver.find_element_by_id("modelnumber").send_keys('5458AC1')
driver.find_element_by_name("submit").click()

is_OS_Present('RHEL Server 2 Skts 1 Guest Prem RH Support 1Yr (5731RSR) ',driver)
is_OS_Present('abc',driver)
Stella
  • 1,504
  • 2
  • 16
  • 25
  • I suggest you profile your code to find out where it's spending most of its time. – martineau Nov 07 '13 at 02:57
  • There is actually a *ton* of stuff going on to check if an element is displayed to a user -> simply because there are many definitions of "displayed". – Arran Nov 07 '13 at 09:29

1 Answers1

0

There is a default timeout as part of Webdriver when it tries to find any element. If the element is present, obviously, it will not timeout. If the element is not present, it will timeout. If I remember correctly, the timeout is a default period of 30seconds.

If you want to select a different timeout period, rather than changing the default which can cause issues elsewhere, it is suggested that you use the WebdriverWait.

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

self.wait = WebdriverWait(self.driver, 10)  //first parameter is your webdriver instance, second is the timeout in seconds

self.wait.until(EC.presence_of_element_located((By.ID, "id")))
assertTrue(self.find_element_by_id("id").is_displayed())

Its a rather rough implementation but hopefully you can see that now Webdriver will wait for 10 seconds for the element to be present, if it is it will then assert whether that element is displayed. If the element is not present, it will throw a timeout exception which could be caught in the normal way instead of blowing up your test.

Mark Rowlands
  • 5,357
  • 2
  • 29
  • 41