Skip to main content
 首页 » 编程设计

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

2025年05月04日30jackei

我正在将我在 Selenium IDE 中编写的测试迁移到 Python WebDriver,但我在 'while' 循环场景中遇到了一些问题。这是 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 block 变得容易:

from selenium.webdriver.support.select import Select 
 
select = Select(driver.find_element_by_name("servers")) 
select_by_visible_text(myServerIP)