小编典典

如何使Selenium单击可变数量的“下一步”按钮?

selenium

我有一个带有模式对话框的内部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()

阅读 464

收藏
2020-06-26

共1个答案

小编典典

弄清楚了。这是相关的代码块:

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中重新搜索。我猜测对话框会重绘,因此您需要再次查找它。

我可以将其重构为更好的外观,但是基本思想就在这里。

2020-06-26