1. 程式人生 > >Selenium入門系列5 下拉列表元素操作

Selenium入門系列5 下拉列表元素操作

鼠標 tag pan inline driver 學習 ima imp inner

本節課程的下拉框是那種默認隱藏,當鼠標移到菜單上下拉框才顯示的。如果直接getelement會報錯,提示元素不可見:


技術分享圖片

so,得先讓下拉列表顯示出來再獲取元素

用到的新知識:

is_display() 是否顯示

webdriver.ActionChains(driver).move_to_element(menu).perform() 鼠標移到menu上

webDriverWait(driver,10).until(條件) 每10s監聽一次,直到條件成立繼續執行後續代碼

腳本學習前,先網上找有下拉菜單的網頁,或者在腳本同一個目錄下新建test2.html,將以下內容拷貝進去保存。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test2</title>
    <style>
    .dropdown{
        postion:relative;
        display: inline-block;
    }

    .dropdownlist{
        display:none;
        postion:absolute;
        background-color
:#f9f9f9; width:160px; } li, li a{padding:10px;} .dropdown:hover{background-color:#ccc;} .dropdown:hover .dropdownlist{display:block;} ul{list-style-type: none} .dropdownlist a:hover{ background-color:#00ffff; } </style> </head> <body>
<div class="dropdown"> <a href="#">link1</a> <ul class="dropdownlist"> <li><a href="#" tabindex="-1">innertext</a></li> <li><a href="#" tabindex="-1">innertext</a></li> <li><a href="#" tabindex="-1">innertext</a></li> <li><a href="#" tabindex="-1">innertext</a></li> <li><a href="#" tabindex="-1">innertext</a></li> <li><a href="#" tabindex="-1">innertext</a></li> <li><a href="#" tabindex="-1">innertext</a></li> <li><a href="#" tabindex="-1">innertext</a></li> </ul> </div> </body> </html>

python腳本:

#coding:utf-8
#下拉列表定位
from selenium import webdriver
import time
import os
from selenium.webdriver.support.ui import WebDriverWait

#打開網頁
driver=webdriver.Firefox()
filepath="file:///"+os.path.abspath("test2.html")
driver.get(filepath)
#鼠標移到link1上顯示下拉框
menu=driver.find_element_by_link_text("link1")
webdriver.ActionChains(driver).move_to_element(menu).perform()
#監聽下拉框是否顯示,顯示則繼續執行代碼
WebDriverWait(driver,10).until(lambda dr:dr.find_element_by_class_name("dropdownlist").is_displayed)
#獲取下拉框的元素,鼠標移動
droplists=driver.find_element_by_class_name("dropdownlist").find_elements_by_tag_name("li")
for li in droplists:
    webdriver.ActionChains(driver).move_to_element(li).perform()

time.sleep(2)
driver.quit()

淘寶首頁 簡單腳本:

#coding:utf-8

from selenium import webdriver
import time

dr=webdriver.Firefox()
dr.get("http://www.taobao.com")

#鼠標移到頂部菜單我的淘寶上
menu=dr.find_element_by_id("J_SiteNavMytaobao")
webdriver.ActionChains(dr).move_to_element(menu).perform()
time.sleep(1)
menu.find_element_by_class_name("site-nav-menu-list").find_element_by_tag_name("a").click()

time.sleep(2)
dr.quit()

Selenium入門系列5 下拉列表元素操作