Selenium操作示例——鼠標懸停顯示二級菜單,再點擊二級菜單或下拉列表


這兩天在玩python中selenium,遇到一個問題,就是鼠標移動到頁面中某按鈕或菜單,自動彈出二級菜單或下拉菜單,再自動點擊其中的二級菜單或下拉列表。

首先,手工操作:打開母校的主頁 http://www.uestc.edu.cn/,將鼠標移動到“學校概括”,自動彈出二級菜單,手工點擊其中的“學校簡介”,彈出學校的簡介。

如何在python中使用selenium自動實現?

# encoding=utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
 
browser = webdriver.Chrome('E:\\chromedriver.exe')
browser.maximize_window()
browser.get('http://www.uestc.edu.cn/')
# 方法一:使用find_element_by_link_text找到頂級菜單,並將鼠標移動到上面
article = browser.find_element_by_link_text(u'學校概況')
ActionChains(browser).move_to_element(article).perform()
# 方法二:使用find_element_by_xpath找到頂級菜單,並將鼠標移動到上面
# article = browser.find_element_by_xpath('//a[contains(@href,"?ch/3")]')
# ActionChains(browser).move_to_element(article).perform()
# 方法一:使用find_element_by_link_text找到二級菜單,並點擊
# menu = browser.find_element_by_link_text(u'學校簡介')
# 方法二:使用find_element_by_xpath找到二級菜單,並點擊
menu = browser.find_element_by_xpath('//li[@classes="first odd nth1"]')
menu.click()
 

程序說明:

1、本程序使用谷歌瀏覽器Chrome,需要下載與Chrome版本對應的驅動程序chromedriver.exe

2、使用兩種方法,找到頂級菜單,並通過move_to_element()和perform()兩個函數實現鼠標懸停

3、使用兩種方法,找到二級菜單,並通過click()函數實現點擊操作


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM