Selenium的waitForElement

我如何编写Selenium的函数来等待只有Python中的类标识符的表? 我有一个学习使用Selenium的Python webdriverfunction的魔鬼。

来自Selenium文档PDF :

import contextlib import selenium.webdriver as webdriver import selenium.webdriver.support.ui as ui with contextlib.closing(webdriver.Firefox()) as driver: driver.get('http://www.google.com') wait = ui.WebDriverWait(driver,10) # Do not call `implicitly_wait` if using `WebDriverWait`. # It magnifies the timeout. # driver.implicitly_wait(10) inputElement=driver.find_element_by_name('q') inputElement.send_keys('Cheese!') inputElement.submit() print(driver.title) wait.until(lambda driver: driver.title.lower().startswith('cheese!')) print(driver.title) # This raises # selenium.common.exceptions.TimeoutException: Message: None # after 10 seconds wait.until(lambda driver: driver.find_element_by_id('someId')) print(driver.title) 

Selenium 2的Python绑定有一个名为expected_conditions.py的新支持类,用于执行各种testing,如testing元素是否可见。 它在这里可用。

注意:上述文件在2012年10月12日之前是在主干中,但还没有在最新的下载中仍然是2.25。 目前为止,直到发布一个新的Selenium版本,你可以保存这个文件到现在,并将其包含在你的导入中,就像我在下面做的那样。

为了让生活变得更简单一些,你可以将一些预期的条件方法和Selenium结合起来, wait until逻辑上做出一些非常方便的函数,就像在Selenium 1中可用的那样。例如,我把它放到我的基类SeleniumTest中我的所有Seleniumtesting课程扩展:

 from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By import selenium.webdriver.support.expected_conditions as EC import selenium.webdriver.support.ui as ui @classmethod def setUpClass(cls): cls.selenium = WebDriver() super(SeleniumTest, cls).setUpClass() @classmethod def tearDownClass(cls): cls.selenium.quit() super(SeleniumTest, cls).tearDownClass() # return True if element is visible within 2 seconds, otherwise False def is_visible(self, locator, timeout=2): try: ui.WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CSS_SELECTOR, locator))) return True except TimeoutException: return False # return True if element is not visible within 2 seconds, otherwise False def is_not_visible(self, locator, timeout=2): try: ui.WebDriverWait(driver, timeout).until_not(EC.visibility_of_element_located((By.CSS_SELECTOR, locator))) return True except TimeoutException: return False 

然后你可以在你的testing中很容易地使用这些:

 def test_search_no_city_entered_then_city_selected(self): sel = self.selenium sel.get('%s%s' % (self.live_server_url, '/')) self.is_not_visible('#search-error') 

我用了很好的经验:

  • time.sleep(秒)
  • webdriver.Firefox.implicitly_wait(秒)

第一个是非常明显的 – 只需等待几秒钟就可以完成一些任务。

对于我所有的selenium脚本,睡眠()几秒钟(范围从1到3),当我在我的笔记本电脑上运行,但在我的服务器上等待的时间有更广泛的范围,所以我也使用implicitly_wait()。 我通常使用implicitly_wait(30),这真的够了。

一个隐含的等待就是告诉WebDriver在查找一个或多个元素(如果不是立即可用的)时轮询DOM一段时间。 默认设置为0.一旦设置,隐式等待就设置为WebDriver对象实例的生命周期。

因为python的selenium驱动不支持这个函数,所以我在python中为wait_for_condition实现了下面的代码。

 def wait_for_condition(c): for x in range(1,10): print "Waiting for ajax: " + c x = browser.execute_script("return " + c) if(x): return time.sleep(1) 

被用作

等待一个ExtJS Ajax调用没有挂起:

 wait_for_condition("!Ext.Ajax.isLoading()") 

一个Javascriptvariables被设置

 wait_for_condition("CG.discovery != undefined;") 

等等

使用Wait Until Page Contains Element与正确的XPath定位器。 例如,给定以下HTML:

 <body> <div id="myDiv"> <table class="myTable"> <!-- implementation --> </table> </div> </body> 

…您可以input以下关键字:

 Wait Until Page Contains Element //table[@class='myTable'] 5 seconds 

除非我遗漏了一些东西,否则不需要为此创build一个新的function。

你总是可以在循环中使用短暂的睡眠,并将它传递给你的元素ID:

 def wait_for_element(element): count = 1 if(self.is_element_present(element)): if(self.is_visible(element)): return else: time.sleep(.1) count = count + 1 else: time.sleep(.1) count = count + 1 if(count > 300): print("Element %s not found" % element) self.stop #prevents infinite loop 

希望这有助于

 from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait driver = webdriver.Firefox() driver.get('www.url.com') try: wait = driver.WebDriverWait(driver,10).until(EC.presence_of_element_located(By.CLASS_NAME,'x')) except: pass 

如果这有助于…

在Selenium IDE中,我添加了…命令:waitForElementPresent目标:// table [@ class ='pln']

然后,我做文件>导出TestCase的Python2(networking驱动程序),它给了我这个…

 def test_sel(self): driver = self.driver for i in range(60): try: if self.is_element_present(By.XPATH, "//table[@class='pln']"): break except: pass time.sleep(1) else: self.fail("time out") 

如果我不知道selenium命令的一些东西,我用firefox的seleniumweb思想RC。 你可以在combobox中select和添加命令,当你完成你的testing用例后,你可以导出testing代码不同的语言。 像java,ruby,phyton,C#等。

更简单的scheme

  from selenium.webdriver.common.by import By import time while len(driver.find_elements(By.ID, 'cs-paginate-next'))==0: time.sleep(100) 

您可以将此function修改为所有types的元素。 下面的代码只是为了类元素:

在“驱动程序”是驱动程序的地方,“element_name”是您正在查找的类名称,“sec”是您愿意等待的最长秒数。

 def wait_for_class_element(driver,element_name,sec): for i in range(sec): try: driver.find_element_by_class_name(element_name) break except: print("not yet") time.sleep(1) 
 WebDriverWait wait = new WebDriverWait(driver, timeout/1000); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(element)));