是否存在支持OR条件的分支等待内置实现方案?
有对应的内置实现,主流网页自动化框架都原生支持等待多个条件中的任意一个满足,不需要自行实现轮询逻辑,不同框架的具体用法如下:
Selenium 实现方案
通过内置的多条件组合方法实现:
- Java 版本使用
ExpectedConditions.or()组合判断逻辑:
import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; // 最长等待10秒,两个元素任意一个存在则结束等待 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.or( ExpectedConditions.presenceOfElementLocated(By.id("result-1")), ExpectedConditions.presenceOfElementLocated(By.id("result-2")) ));
- Python 版本使用
expected_conditions.any_of组合判断逻辑:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) wait.until(EC.any_of( EC.presence_of_element_located((By.ID, "result-1")), EC.presence_of_element_located((By.ID, "result-2")) ))
等待结束后会返回第一个匹配到的元素,你可以直接根据返回值判断触发的是哪一种结果。
Playwright 实现方案
直接在选择器中用逗号分隔多个元素选择规则即可,框架会自动等待任意一个匹配元素出现:
// 自定义超时为10秒,默认超时为30秒 const element = await page.waitForSelector('#result-1, #result-2', { timeout: 10000 });
Python 版本写法一致:
element = page.wait_for_selector('#result-1, #result-2', timeout=10000)
Cypress 实现方案
直接给 cy.get() 传入逗号分隔的多选择器即可,框架会自动等待到超时时间结束前的任意一个匹配元素出现:
// 自定义超时为10秒,默认超时为4秒 cy.get('#result-1, #result-2', { timeout: 10000 }).then(($el) => { // 后续处理逻辑 })
内容的提问来源于stack exchange,提问作者asdasd31
相关产品推荐
相关产品推荐

