处理下拉菜单思路:点击这个按钮,等待下拉菜单显示出来,然后使用层级定位方法来获取下拉菜单中的具体项。
这段代码有两处需要指出,是我执行遇到问题给大家一个提醒。
1. 如我下面标注的。unittest里对于类的方法是按字母顺序执行的。当时我定义的def login 和 def homepage就会一直报找不到element的问题,因为先执行homepage后执行登录,所以下拉菜单元素找不到。
2. 对于xpath不熟悉可以先用一个简单方法找到xpath。以chrome为例。
a. 找到要定位元素,右键-检查
b. 在html中找到要定位元素的element,右键-Copy-Copy XPath,获得xpath,粘贴即可。
#!/user/bin/env python
# coding = utf-8
import unittest
import time
from selenium import webdriverfrom selenium.common.exceptions
import NoSuchElementExceptionfrom selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
# ***类里的方法是按字母顺序执行的***
class SearchTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# create a new Firefox session """
cls.driver = webdriver.Chrome()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
def test_homepage_login(self):
self.driver.get("url")
self.driver.find_element_by_id("login_account").send_keys("account")
self.driver.find_element_by_id("login_password").send_keys("password")
self.driver.find_element_by_id("loginBtn").click() time.sleep(3)
self.assertTrue(self.is_element_present(By.ID, "exitBtn"))
def test_homepage_menu(self):
# 点击下拉菜单
self.elem = self.driver.find_element_by_xpath("//*[@id='navUl']/li[2]") self.elem.click()
# 找到nav-con-list父元素
WebDriverWait(self.driver, 10).until(lambda the_driver: the_driver.find_element_by_class_name("nav-con-list").is_displayed())
time.sleep(3)
# 找到终端管理,为了便于观察结果sleep 15s
self.driver.find_element_by_class_name("nav-con-list").find_element_by_xpath("//*[@id = 'terminalMage']/a").click()
time.sleep(15)
@classmethod
def tearDownClass(cls):
# close the browser window
cls.driver.quit()
def is_element_present(self, how, what):
"""
Utility method to check presence of an element on page
:params how: By locator type
:params what: locator value
"""
try:
self.driver.find_element(by=how, value=what)
except NoSuchElementException:
return False
return True
if __name__ == "__main__":
unittest.main(verbosity=2)