我正在将我在Selenium IDE中编写的测试迁移到Python WebDriver,并且我遇到了一些'而非循环场景的问题。这是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等)。虽然地址列在服务器列表框中,但对象“//选择[@ 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,这样一旦删除了所有服务器名称,它就会优雅地退出。
答案 0 :(得分:1)
制作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)