gpt4 book ai didi

python - 如何使用 Selenium 让 WebDriverWait 返回元素而不是 Python 中的 bool 值

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:46 24 4
gpt4 key购买 nike

现在,我有一个方法,可以使用以下方法等待元素可见:

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

这可以正常工作;但是,它返回一个 bool 值,而不是它找到的元素。我希望它在找到该元素后返回该元素。我正在通过以下方式执行此操作:

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

最佳答案

使用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()

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

关于python - 如何使用 Selenium 让 WebDriverWait 返回元素而不是 Python 中的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32057220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com