当EC返回elemen时python selenium WebDriverWait不工作

2024-06-08 08:49:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用过很多selenium,但没有机会使用WebDriverWait。现在我需要点击一个后退按钮,虽然它似乎是立即可用的,它必须偶尔不是一瞬间。我可以用一个时间。睡觉(1) 它偶尔会循环一次。我可以接受这一点,但我认为这是实现WebDriverWait的最佳机会。 这是有效的:

browser.find_element_by_xpath('//div[@onclick="backToResults();"]')

除了偶尔的无忧无虑的例外。。。

这不起作用,它只运行3秒并超时(不管我尝试了多长时间,它都不会成功返回):

^{pr2}$

…但是没有wait的同一个ec调用确实返回了元素,因此wait应该有效:

ec.presence_of_element_located((By.XPATH, '//div[@onclick="backToResults();'))

所以,并不是元素不在那里并且可以访问,至少在一秒钟左右,但是WebDriverWait没有从积极的EC调用返回?


Tags: divbrowser元素byselenium时间elementfind
2条回答

不确定是否将EC分配给变量是一个好的实践。。。在

{{cd1>删除这个位有帮助。在

而且,似乎行-ec.presence_of_element_located((By.XPATH, '//div[@onclick="backToResults();'))-起作用了,所以我想知道这里的问题是什么。。。?:)

在时间。睡觉()/无接触异常

要将webdriver的执行挂起毫秒,可以按如下方式传递number of seconds或{}:

import time
time.sleep(1) #sleep for 1 sec
time.sleep(0.25) #sleep for 250 milliseconds

然而,当使用WebDriver来实现自动化时,使用time.sleep(secs)而没有任何特定的条件来实现自动化的目的,因此应不惜任何代价加以避免。根据文件:

time.sleep(secs) suspends the execution of the current thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

因此,有时甚至在使用time.sleep(secs)之后,您可能会看到NoSuchElementException

现在,由于您的目标是在元素上调用click(),因此您需要使用element_to_be_clickable(locator)而不是使用期望的条件作为presence_of_element_located(),如下所示:

^{pr2}$

您可以在How to sleep webdriver in python for milliseconds中找到相关的详细讨论

相关问题 更多 >