Selenium等待所有指定的Web元素更改或消失

问题描述 投票:0回答:2

假设有一个HTML块

<div id='list'>
   <p>hello</p>
   <div class='locked'>world</div>
   <p>你好</p>
   <div class='locked'>世界</div>
</div>

如何在python中使用硒来等待一段时间,直到all <div class='locked'>标签变成别的东西。(例如<div class='unlock'>xxx</div>

谢谢!

python selenium xpath css-selectors webdriverwait
2个回答
1
投票
一个人可以编写自定义的预期条件,以检查您需要达到的特定状态。就像在您的方案中一样,您希望状态或类处于锁定状态的控件的计数为0,以便继续进行操作。我已经给出了可用于自定义同步功能的代码示例我是基于python的Selenium的新手,但它假定您正在使用xpath来标识锁定状态控件,这应该可以解决问题。

------------用Python代码更新---------------------------

from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC class WaitForLockStateChange: def __init__(self, locator, val_): self.locator = locator def __call__(self, driver): elems = driver.find_elements_by_xpath(self.locator) if len(elems)<1: return True else: return False wait = WebDriverWait(driver, 10) element = wait.until(WaitForLockStateChange("//div[@class='locked']"))


0
投票
我有一个出于类似目的创建的自定义生成的类(对我来说,我对“ value”属性的更改很感兴趣,但是我对其进行了修改以适合您的“ class”更改示例):

from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC class WaitForAttrValueChange: def __init__(self, locator, val_): self.locator = locator self.val = val_ def __call__(self, driver): try: attr_value = EC._find_element(driver, self.locator).get_property('className') return attr_value.startswith(self.val) except SE.StaleElementReferenceException: return False

然后您可以将其与WebDriverWait一起使用(显然,您可以使用任何By识别方法代替By.ID,这只是一个示例):

WebDriverWait(driver, 20).until(WaitForAttrValueChange((By.ID, 'id'), 'locked'))


0
投票
Selenium一起使用以等待所有<div class='locked'>标签变为<div class='unlock'>xxx</div>,您必须为visibility_of_all_elements_located()引入

WebDriverWait,并且可以使用以下任何一个Locator Strategies:] >

  • 使用CSS_SELECTOR

WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div#list div.unlock")))

  • 使用XPATH
  • WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@id='list']//div[@class='unlock']")))

  • :您必须添加以下导入:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
    © www.soinside.com 2019 - 2024. All rights reserved.