假设有一个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代码更新---------------------------
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']"))
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'))
<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