<div id="loader-mid" style="position: absolute; top: 118.5px; left: 554px; display: none;">
<div class="a">Loading</div>
<div class="b">please wait...</div>
</div>
并希望等到它消失。我有以下代码,但它有时等待太长时间,在某些代码点它会突然冻结所有进程,我不知道为什么。
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
self.wait = WebDriverWait(driver, 10)
self.wait.until(EC.invisibility_of_element_located((By.XPATH, "//*[@id='loader_mid'][contains(@style, 'display: block')]")))
我也试过这个:
self.wait.until_not(EC.presence_of_element_located((By.XPATH, "//*[@id='loader_mid'][contains(@style, 'display: block')]")))
我不确切知道如何检查,但也许我的元素总是出现在页面上,而selenium认为它就在那里,唯一改变的是参数显示从无到块的变化。我想我可以获得像字符串这样的属性并检查是否有单词&#34; block&#34;但是我错了......请帮帮我。
答案 0 :(得分:6)
重申您的答案(通过一些错误处理),以便人们更容易找到解决方案:)
最终变量
SHORT_TIMEOUT = 5 # give enough time for the loading element to appear
LONG_TIMEOUT = 30 # give enough time for loading to finish
LOADING_ELEMENT_XPATH = '//*[@id="xPath"]/xPath/To/The/Loading/Element'
在py文件中的其他地方编码
try:
# wait for loading element to appear
# - required to prevent prematurely checking if element
# has disappeared, before it has had a chance to appear
WebDriverWait(driver, SHORT_TIMEOUT
).until(EC.presence_of_element_located((By.XPATH, LOADING_ELEMENT_XPATH)))
# then wait for the element to disappear
WebDriverWait(driver, LONG_TIMEOUT
).until_not(EC.presence_of_element_located((By.XPATH, LOADING_ELEMENT_XPATH)))
except TimeoutException:
# if timeout exception was raised - it may be safe to
# assume loading has finished, however this may not
# always be the case, use with caution, otherwise handle
# appropriately.
pass
答案 1 :(得分:1)
以下代码创建一个无限循环,直到元素消失:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
while True:
try:
WebDriverWait(driver, 1).until(EC.presence_of_element_located((By.XPATH, 'your_xpath')))
except TimeoutException:
break
答案 2 :(得分:0)
使用预期的条件:invisibility_of_element_located
这对我来说很好。
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
WebDriverWait(driver, timeout).until(EC.invisibility_of_element_located((By.ID, "loader-mid")))