Bre*_*dly 42 python automation automated-tests selenium-webdriver
如何为Selenium编写函数以等待Python中只有类标识符的表?我有一个学习使用Selenium的Python webdriver功能的魔鬼.
unu*_*tbu 53
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)
Run Code Online (Sandbox Code Playgroud)
Dav*_*Koo 20
Selenium 2的Python绑定有一个名为expected_conditions.py的新支持类,用于执行各种操作,例如测试元素是否可见.它可以在这里找到.
注意:上述文件自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
Run Code Online (Sandbox Code Playgroud)
然后,您可以在测试中轻松使用这些:
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')
Run Code Online (Sandbox Code Playgroud)
我使用过以下方面的经验:
第一个是非常明显的 - 只需等待几秒钟即可.
对于我的所有Selenium脚本,sleep()有几秒钟(范围从1到3),当我在笔记本电脑上运行它时,但在我的服务器上,等待的时间范围更广,所以我也使用implicitly_wait().我通常使用implicitly_wait(30),这已经足够了.
隐式等待是指在尝试查找一个或多个元素(如果它们不是立即可用)时,WebDriver轮询DOM一段时间.默认设置为0.设置后,将为WebDriver对象实例的生命周期设置隐式等待.