虽然声明未对 Selenium Webdriver 评估为 false

While statement not evaluating to false for Selenium Webdriver

我正在将我在 Selenium IDE 中编写的测试迁移到 Python WebDriver,我遇到了一些 'while'[=30 的问题=] 循环场景。这是 IDE 代码:

while | selenium.isElementPresent("xpath=//select[@name='servers']/option")
   storeValue | //select[@name='servers']/option | myServerIP
   waitForElementPresent | name=servers
   addSelection | name=servers | ${myServerIP}
   waitForValue | //input[@value='Delete'] | Delete
   clickAndWait | //input[@value='Delete']
   waitForNotText | //select[@name='servers']/option | ${myServerIP}
endWhile

我有一个框,其中包含已输入的时间服务器地址(即 129.6.15.30、time-d.nist.gov 等)。当服务器列表框中列出地址时,对象 "//select[@name='servers']/option" 存在。删除所有服务器后,该对象将不复存在。

当服务器列表对象存在时..

  • 在列表中存储顶级服务器的名称。
  • 选择该服务器。
  • 从列表中删除该服务器
  • 确认服务器名称已从列表中删除

当我尝试将此场景迁移到 WebDriver 时,我遇到了一些问题。

while expected_conditions.visibility_of_element_located("//select[@name='servers']/option"):
   myServerIP = driver.find_element_by_xpath("//select[@name='servers']/option").text
   assertExpectedConditionTrue(driver, "By.NAME", "servers")
   driver.find_element_by_xpath("//select[@name='servers']/option[contains(text(), '"+ myServerIP + "')]").text
   driver.find_element_by_xpath("//select[@name='servers']/option[contains(text(), '"+ myServerIP + "')]").click()
   assertExpectedValueConditionTrue(driver, "By.XPATH", "//input[@value='Delete']", "Delete")
   driver.find_element_by_xpath("//input[@value='Delete']").click()
   assertExpectedConditionFalse(driver, "By.XPATH", "//select[@name='servers']/option", myServerIP)

服务器名称找到并删除就好了。但是,'while' 部分似乎永远不会评估为不可见,这会导致 NoSuchElementException 失败(在 'while' 循环的第一行)一旦所有服务器名称被删除。我正在寻找一种方法使 'while' 循环评估为 false,以便在删除所有服务器名称后正常退出。

创建一个 while True 循环并在获得 TimeoutException:

后退出循环
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 10)
while True:
    try:
        wait.until(EC.presence_of_element_located((By.XPATH, "//select[@name='servers']/option")))
    except TimeoutException:
        break
    # rest of the code

或者,或者,捕获 NoSuchElementException:

from selenium.common.exceptions import NoSuchElementException

while True:
    try:
        myServerIP = driver.find_element_by_xpath("//select[@name='servers']/option").text
    except NoSuchElementException:
        break

此外,selenium 有这个 Select class 可以很容易地使用 select->option HTML 块:

from selenium.webdriver.support.select import Select

select = Select(driver.find_element_by_name("servers"))
select_by_visible_text(myServerIP)