如何检测隐藏按钮?

How to detect a hidden button?

我有一个按钮:当我点击它时,它会发送一个 ajax 请求,然后 javascript 代码会在该按钮上添加 class “隐藏”完成了。

如何等待 ajax 请求结束?发送点击命令后,我认为 Selenium 应该检测何时将“隐藏”class 添加到按钮,但我不知道如何检测。

你能帮帮我吗?

没用(我有超时):

driver.find_element(By.ID, "saveButton").click()
wait = WebDriverWait(driver, 20)
wait.until(driver.find_element_by_xpath("//button[@id='saveButton' and contains(@class, 'hide')]"))

我不知道是否还有其他答案,但是在循环中等待这个怎么样?

while True:
    time.sleep(0.25)
    try:
        #try to get button
        break
    except:
        continue

或者您可以使用 if 条件检查按钮是否可用。

while True:
    time.sleep(0.25)
    if button:
        break

希望你明白我的意思。它也可以有另一种方法...

使用预期条件 presence_of_element_located()visibility_of_element_located()

 wait = WebDriverWait(driver, 20)
 wait.until(EC.presence_of_element_located((By.XPATH, "//button[@id='saveButton' and contains(@class, 'hide')]")))

wait = WebDriverWait(driver, 20)
wait.until(EC.visibility_of_element_located((By.XPATH, "//button[@id='saveButton' and contains(@class, 'hide')]")))

您需要导入以下库。

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

你也可以试试这个:

wait = WebDriverWait(driver, 10)
        wait.until(lambda driver: driver.execute_script("return jQuery.active == 0"))

但是,我会选择等待您要与之交互的下一个元素。 例如,接下来您需要单击带有 some_id 的按钮。那么,就等着吧:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#some_id")))
element.click()

您可以等待元素不可见:

driver.find_element(By.ID, "saveButton").click()
wait = WebDriverWait(driver, 20)
wait.until(EC.invisibility_of_element_located((By.ID, "saveButton"))) 

但是如果您想了解更多有关 AJAX 调用的信息,您应该考虑使用代理: