如何让Selenium点击可变数量的“下一个”按钮?

时间:2013-04-05 00:47:05

标签: python selenium selenium-webdriver

我有一个内部Web应用程序,它有一个模态对话框。不幸的是,我不能在这里发布实际的Web应用程序位置,但让我尽可能地描述它。

  • 当应用程序启动时,屏幕上会出现一个方框,告诉您一堆文本。您可以按“下一步”以获取下一页文本。
  • 在最后一页上,“下一步”按钮被禁用,并且启用了Web应用程序的其余UI。
  • 页面数量可变,所以我不知道有多少次点击“下一步”。

我可以点击固定的次数(例如:如果我知道有两个页面我可以点击两次)但我不确定如何改变它以便无论页数是多少我都会运行有。我想要一个普遍的解决方案;大概这会使用某种循环来检查按钮是否已启用。如果是,则单击它。如果它被禁用,则退出循环。

问题是:如何在Selenium中设置一个循环,重复点击按钮直到它被禁用?

这是我尝试过的代码:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

driver.get("http://localhost/myapp")

try:
    wait = WebDriverWait(driver, 100)    
    wait.until(EC.element_to_be_clickable((By.ID,'menuIntroBox_buttonNext')))    
    driver.find_element_by_id("menuIntroBox_buttonNext").click()

    # Click through the introduction text... this is the problematic code.
    # Here I tried to wait for the element to be clickable, then tried to do a while 
    # loop so I can click on it as long as it's clickable, but it never seems to do the
    # break.
    wait.until(EC.element_to_be_clickable((By.ID,'main_buttonMissionTextNext')))
    while EC.element_to_be_clickable((By.ID,'main_buttonMissionTextNext')):
        element = driver.find_element_by_id("main_buttonMissionTextNext")
        element.click()
        print "Waiting until it's clickable."

        if not element.is_enabled():
            break

    print "Here is where I'd do other stuff.... the stuff I want to actually do in the test case."
finally:
    driver.quit()

2 个答案:

答案 0 :(得分:2)

想出来。这是相关的代码块:

wait.until(EC.element_to_be_clickable((By.ID, 'main_buttonMissionTextNext')))
while EC.element_to_be_clickable((By.ID,'main_buttonMissionTextNext')):
    driver.find_element_by_id("main_buttonMissionTextNext").click()
    if not driver.find_element_by_id("main_buttonMissionTextNext").click().is_enabled():
        break
    wait.until(EC.element_to_be_clickable((By.ID, 'main_buttonMissionTextNext')))

我发现了两件事:

  1. 您可以使用is_enabled()检查元素是否已启用。
  2. 点击后,您必须重新搜索DOM元素。我猜这个对话框重绘了,所以你需要再次找到它。
  3. 我可能会重构这个看起来更好但现在基本的想法就在这里。

答案 1 :(得分:0)

While driver.find_element_by_id("main_buttonMissionTextNext").isEnabled() {
  driver.find_element_by_id("main_buttonMissionTextNext").click();
  sleep(1);
}

//sleep function is in java, so you can "translate" it in python 
void sleep(int i){
  driver.manage().timeouts().implicitlyWait(i, TimeUnit.SECONDS);
}

尝试并告诉我发生了什么事。