docs说:
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available.
子问题:
在find_elements_by_
的情况下(复数),有多少元素implicit_wait
在继续你的脚本之前等待存在?或者 implicit_wait
仅适用于 find_element_by_
(单数)?如果是这样,文档中的“或元素”是什么意思?
来自 an SO answer我读到最好不要在同一个脚本中同时使用隐式和显式等待,我注意到了这一点,因为我希望测试尽可能健壮。
因为我知道有时候我肯定需要 WebDriverWait
, 这是否意味着我需要摆脱 implicit_wait
在我的 unittest
setUp
方法,而是使用 WebDriverWait
每次我使用任何 find_element_by_
方法?
(我宁愿不必这样做;虽然我想我可以将每个 find_element_by_
方法放在我自己的自定义函数中 - 每个都包含在自己的 WebDriverWait
中 - 但感觉我不应该这样做到)。
所以我的主要问题是:
我可以保留我的 implicit_wait
吗?在我的测试中setUp
方法,然后只使用 WebDriverWait
说到find_elements_by_
以及我知道我需要它的其他地方?
最佳答案
Since I know there are times I'll definitely need WebDriverWait, does this mean I need to get rid of implicit_wait in my unittest setUp method and instead employ WebDriverWait every single time I use any find_element_by_ method?
是的。正如您在链接到的问题中看到的那样,如果您同时使用这两种类型的等待,您将遇到不良行为。这不仅仅是理论上的。我亲身经历过这种行为,尝试对其进行调试,找到您链接到的问题,然后从我的测试套件中删除了所有隐式等待。
我开发了一个 library帮助设置显式等待(并做很多其他事情)。假设您已经有一个包含 selenium 网络驱动程序的 driver
对象:
from selenium.webdriver.common.by import By
import selenic.util
util = selenic.util.Util(driver)
# This goes through util and uses the explicit wait set by util.
foo = util.find_element((By.CSS_SELECTOR, "..."))
# For special cases that take longer to give results.
with util.local_timeout(10):
# The timeout is set to 10 for calls in this with block.
bar = util.find_element(...)
# The timeout is restored to what it was just before the with.
有些时候您根本不需要使用等待,因为逻辑上如果元素 A 存在则 B 也存在,因此您不必等待 为它。例如。如果你想要一个你已经从 Selenium 获得的元素的父元素,你可以做 parent = foo.find_element_by_xpath("..")
。
对于find_elements
的行为,只要判断有结果就返回。这可能意味着如果在 find_elements
找到要返回的内容后后面的元素确实出现,则只获取一个元素。
关于python - 混合隐式和显式等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20268396/