#!/usr/bin/env/python3 # -*- coding:utf-8 -*- ''' Author:leo Date&Time:2019-07-28 and 10:02 FileName:20190728_華爲官網二級菜單懸停和窗口切換.py Description:Python3.5+selenium3.0
''' ''' -- 情景CSS定位、懸停、校驗 1.登錄華爲官網 https://www.vmall.com/, 2.點擊 "華爲官網" 鏈接 3.檢查 "華爲官網" 頁面上是否 有如下主菜單:智能手機/筆記本/平板/穿戴設備/智能家居/更多產品/軟件應用/服務與支持 4.最後再回到主窗口, 檢查鼠標停留在 "筆記本&平板" 處的時候, 是否顯示的菜單有:"平板電腦 筆記本電腦 筆記本配件" 5.模擬懸停操作,打印二級菜單信息 ''' from selenium import webdriver from time import sleep driver = webdriver.Chrome() driver.get("https://www.vmall.com/") # 獲取當前窗口句柄 mainHandle = driver.current_window_handle driver.implicitly_wait(5) # 點擊華爲官網鏈接跳轉 driver.find_element_by_xpath("//div[@class='s-sub']//li[2]/a").click() sleep(3) driver.maximize_window() # 獲取所有窗口句柄 allHandles = driver.window_handles print("主窗口爲:"+driver.title) # 切換瀏覽器窗口 for handle in allHandles: driver.switch_to.window(handle) if "華爲消費者業務官網" in driver.title: # --這裏要用driver.title,不用帶括號() # driver.switch_to_window(i) # --這個新版本已經廢棄,需要用driver.switch_to.window(i) print("新窗口爲: "+driver.title) break # menuTops = driver.find_elements_by_css_selector(".left-box .clearfix.nav-cnt li") # --css用法 menuTops = driver.find_elements_by_xpath("//div[@class='left-box']//ul[@class='clearfix nav-cnt']/li") menuList = [] for j in menuTops: menuName = j.find_element_by_tag_name("a").text menuList.append(menuName) # 檢查點 chckin = "智能手機/筆記本/平板/穿戴設備/智能家居/更多產品/軟件應用/服務與支持" menuList = "/".join(menuList) print(f"\n當前菜單爲:\n{menuList}") if chckin ==menuList: print("\nPass the testcase!----------:\n{chckin}\n{menuList}") else: print(f"\nFail the testcase!----------:\n{chckin}\n{menuList}") # 切回主窗口 for handle2 in allHandles: driver.switch_to.window(handle2) if handle2 == mainHandle: print(f"\n歡迎回到主窗口:{driver.title}") break # 導入鼠標懸停類 from selenium.webdriver import ActionChains # 定位鼠標懸停位置 sleep(3) mouseAddr = driver.find_element_by_css_selector("#zxnav_1") # 懸停到目標區域 ActionChains(driver).move_to_element(mouseAddr).perform() # 定位目標子區域並打印信息 mouseMenus = driver.find_elements_by_css_selector("#zxnav_1 div.category-panels.category-panels-1 li span") print("\n懸停打印開始:") mainMenu = "/".join([m.text for m in mouseMenus]) print(mainMenu+"\n") # 檢查點 check2 = "平板電腦/筆記本電腦/筆記本配件" if mainMenu == check2: print(f"Pass the testcase!----------\n{check2}\n{mainMenu}") else: print(f"Fail the testcase!---------- Please check your daima:\n{check2}\n{mainMenu}")
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
主窗口爲:華爲商城(VMALL.COM)_華爲手機、榮耀手機、官網正品保障
新窗口爲: 華爲消費者業務官網-華爲智能手機 | HUAWEI P30 系列
當前菜單爲:
智能手機/筆記本/平板/智能穿戴/智能家居/更多產品/軟件應用/服務與支持
Fail the testcase!----------:
智能手機/筆記本/平板/穿戴設備/智能家居/更多產品/軟件應用/服務與支持
智能手機/筆記本/平板/智能穿戴/智能家居/更多產品/軟件應用/服務與支持
歡迎回到主窗口:華爲商城(VMALL.COM)_華爲手機、榮耀手機、官網正品保障
懸停打印開始:
平板電腦/筆記本電腦/筆記本配件
Pass the testcase!----------
平板電腦/筆記本電腦/筆記本配件
平板電腦/筆記本電腦/筆記本配件
Process finished with exit code 0