Selenium waitForElement

问题描述 投票:41回答:11

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

python selenium-webdriver automation automated-tests
11个回答
47
投票

来自Selenium Documentation 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)

0
投票

更轻松的解决

    from selenium.webdriver.common.by import By    
    import time

    while len(driver.find_elements(By.ID, 'cs-paginate-next'))==0:
        time.sleep(100)

0
投票

您可以将此功能修改为所有类型的元素。下面的内容仅适用于class元素:

“driver”是驱动程序,“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)

19
投票

Selenium 2的Python绑定有一个名为expected_conditions.py的新支持类,用于执行各种操作,例如测试元素是否可见。这是available here.

注意:上述文件自2012年10月12日起在主干中,但尚未在最新下载中仍为2.25。暂时发布新的Selenium版本,您现在可以在本地保存此文件并将其包含在您的导入中,就像我在下面所做的那样。

为了让生活更简单,你可以将这些预期条件方法中的一些与Selenium wait until逻辑结合起来,制作一些非常方便的函数,类似于Selenium 1中可用的函数。例如,我将它放入我的基类SeleniumTest中我的Selenium测试类的扩展:

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

然后,您可以在测试中轻松使用这些:

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

7
投票

我使用过以下方面的经验:

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

第一个是非常明显的 - 只需等待几秒钟即可。

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

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


2
投票

我为wait_for_condition的python实现了以下内容,因为python selenium驱动程序不支持此函数。

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

设置了一个Javascript变量

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

等等


1
投票

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

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

...您可以输入以下关键字:

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

除非我错过了什么,否则无需为此创建新功能。


1
投票

如果这有帮助......

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

然后我做了File> Export TestCase As Python2(Web Driver),它给了我这个......

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

1
投票

您总是可以在循环中使用短暂睡眠并将其传递给您的元素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

1
投票

希望这会有所帮助

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


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

0
投票

如果我对selenium命令一无所知,我使用selenium web idea RC和firefox。您可以在组合框中选择并添加命令,并在完成测试用例后可以导出测试代码不同的语言。像java,ruby,phyton,C#等。

© www.soinside.com 2019 - 2024. All rights reserved.