如何使用Selenium

时间:2015-08-17 18:26:16

标签: python selenium

现在,我有一个等待元素可见的方法:

WebDriverWait(self.driver, seconds).until(lambda s: s.find_element_by_xpath(path).is_displayed())

这很正常;但是,它返回一个布尔值,而不是它找到的元素。我希望它一旦找到就返回该元素。我这样做有以下几点:

def waituntil(path, seconds):
    WebDriverWait(self.driver, seconds).until(lambda s: s.find_element_by_xpath(path).is_displayed())
    ret = self.driver.find_element_by_xpath(path)
    return ret

当然,这很有效。不幸的是,它需要Selenium两次找到相同的元素,这增加了等待时间(无论多小)。有没有办法通过只查找一次元素,使用waituntil(或类似功能)返回一个web元素?所以可以允许以下内容:

ret = WebDriverWait(self.driver, seconds).until(lambda s: s.find_element_by_xpath(path).is_displayed())
ret.click()

我目前正在使用:

Python 2.7
Windows 7
Selenium 2.4.4
Firefox 35.0.1

1 个答案:

答案 0 :(得分:1)

使用selenium.webdriver.support.expected_conditions.presence_of_element_located

基于the unofficial docs

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
ret = WebDriverWait(self.driver, seconds).until(
    expected_conditions.presence_of_element_located((By.XPATH, path)))
ret.click()

(为了清楚起见,省略了其他导入和初始化,因为您似乎有这些工作。如果您遇到问题,请参阅前面的链接。)