简体   繁体   English

Python Selenium:等待一个元素或另一个元素加载

[英]Python Selenium: waiting for one element OR another element to load

I'm using this code for waiting for an element to load:我正在使用此代码等待元素加载:

browser = webdriver.Chrome(executable_path=chromedriver,options=ChromeOpts, desired_capabilities=captain) 
wait = WebDriverWait(browser, 5)
openbrowser = browser.get(url) 
wait.until(EC.presence_of_element_located((By.ID, 'h1')))
browser.execute_script("window.stop();")

However, what I really need is to wait for one element OR another.但是,我真正需要的是等待一个元素或另一个元素。 So I can, for example, wait for 'h1' OR 'rf-footer'.因此,例如,我可以等待“h1”或“rf-footer”。

thanks,谢谢,

You can combine the two checks in a single wait() operation - by using a python's lambda expression, using the find_elements_*() methods glued together with an or :您可以在单个wait()操作中组合这两个检查 - 通过使用 python 的 lambda 表达式,使用find_elements_*()方法与 an or粘合在一起:

element = wait.until(lambda x: x.find_elements_by_id("id1") or x.find_elements_by_css_selector("#id2"))[0]

You can use this approach even to get the element that is matched first - the [0] at the end.您甚至可以使用这种方法来获取最先匹配的元素 - 最后的[0]
This solution works, as find_elements_*() returns a list of all matched elements, or an empty one if there aren't such (a boolean false).此解决方案有效,因为find_elements_*()返回所有匹配元素的列表,如果不存在,则返回空列表(布尔值 false)。 So if the first call doesn't find anything, the second is evaluated;因此,如果第一个调用没有找到任何东西,则评估第二个调用; that repeats until either of them finds a match, or the time runs out.重复直到他们中的任何一个找到匹配项,或者时间用完。

This approach gives the benefit the wait.until() will stop immediately after one of the two passes - eg speed.这种方法的好处是wait.until()将在两次传递之一后立即停止 - 例如速度。


Versus a try-catch block - in it, the first condition has to fail (waited for up to X seconds, usually 10), for the second one even to be checked;与 try-catch 块相比 - 在其中,第一个条件必须失败(最多等待 X 秒,通常为 10 秒),甚至要检查第二个条件; so if the first is false, while the second true - the runtime/wait is going to be at least X seconds plus whatever time the second check takes.因此,如果第一个为假,而第二个为真 - 运行时/等待将至少为 X 秒加上第二次检查所需的时间。
In the worst case, when both are false, you are in for 2X wait, versus X in combining the two.在最坏的情况下,当两者都为假时,您需要等待 2 倍的等待,而将两者结合起来则为 X。 If you add other conditions, you are only increasing the factor.如果添加其他条件,则只会增加因子。

You can do this by using expected_conditions您可以通过使用expected_conditions来做到这一点

from selenium.webdriver.support import expected_conditions

the full solution can be found here: Selenium Expected Conditions - possible to use 'or'?完整的解决方案可以在这里找到: Selenium 预期条件 - 可以使用“或”吗?

I got it buy using TRY/EXCEPT.我是用 TRY/EXCEPT 买的。

openbrowser = browser.get(url) #navigate to the page 
try: 
   wait.until(EC.presence_of_element_located((By.ID, id_stop))) 
except: 
   wait.until(EC.presence_of_element_located((By.ID, 'rf-footer')))
browser.execute_script("window.stop();")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM