1. 程式人生 > >selenium + python 滑鼠點選事件

selenium + python 滑鼠點選事件

對滑鼠的點選事件做了一些瞭解,從百度發現有很多相關內容

參考文章https://www.ibm.com/developerworks/cn/java/j-lo-keyboard/ 和 http://blog.csdn.net/liujingqiu/article/details/50475833

首先引入模組 from selenium.webdriver.common.action_chains import ActionChains

#滑鼠雙擊事件
double = driverChrome.find_element_by_xpath('//*[@id="dynamicLayout_0"]/div/div/dl/dt/a')
ActionChains(driverChrome).double_click(double).perform()
# 拖動
source = driverChrome.find_element_by_xpath('path1')
target = driverChrome.find_element_by_xpath('path2')
ActionChains(driverChrome).drag_and_drop(source, target).perform()
#滑鼠移到元素上
above = driverChrome.find_element_by_xpath('//*[@id="dynamicLayout_0"]/div/div/dl/dd[2]/span/i')
ActionChains(driverChrome).move_to_element(above).perform()
#滑鼠移右擊事件
right = driverChrome.find_element_by_xpath('//*[@id="layoutMain"]/div/div[2]/div/div/div[4]/div/div/dd/div[2]')
ActionChains(driverChrome).context_click(right).perform()
#單擊hold住
left_hold = driverChrome.find_element_by_xpath('path')
ActionChains(driverChrome).click_and_hold(left_hold).perform()

在百度雲盤的情景下,用了雙擊事件,滑鼠移到元素上,以及滑鼠右鍵的操作,拖動以及滑鼠左鍵hold還沒嘗試
在場景應用中又遇到一些問題進行了擴充套件,下面程式碼是基於上一次程式碼接著的:
#滑鼠雙擊
double = driverChrome.find_element_by_xpath('//*[@id="dynamicLayout_0"]/div/div/dl/dt/a')
ActionChains(driverChrome).double_click(double).perform()
print("雙擊成功")
sleep(5)

#滑鼠移動
above = driverChrome.find_element_by_xpath('//*[@id="dynamicLayout_0"]/div/div/dl/dd[2]/span/i')
ActionChains(driverChrome).move_to_element(above).perform()
print("移動成功")
sleep(5)


#嘗試層級定位,定位左側音樂文字連結
uClass = driverChrome.find_element_by_class_name('fOHAbxb')
liList = uClass.find_elements_by_tag_name('li') #定位一組li
for li in liList:
    if li.get_attribute('data-key') =='music':  #音樂選項
li.click()

#定位右側第一條音樂資訊
musicL = driverChrome.find_element_by_class_name("NHcGw")
musicList = musicL.find_elements_by_tag_name("dd")
for d in musicList:
    if d.get_attribute('_position')=='0':
        print("獲得第一首歌")
        #d.click()
ActionChains(driverChrome).move_to_element(d).perform()
        ActionChains(driverChrome).context_click(d).perform()  # 點選右鍵
sleep(3)
#彈出框定位
element1 =  driverChrome.find_element_by_class_name("list")
#定位
sleep(5)
liEliment = element1.find_elements_by_tag_name('li')
for li in liEliment:
    if li.text =='下載':
        li.click()
print("右擊成功")

在這次程式碼中,本來都是採用的xpath定位,但是在執行指令碼過程中xpath定位總是有時成功,有時候會提示找不到該元素,本來以為都是由於頁面載入或者等待時間不夠長
造成,但是通過詢問得出還有可能是動態元素,xpath的值會改變,經過百度,暫且使用了一種方法:層級定位。
但是第二天在公司電腦上使用的時候又出現不能定位的情況,得到一些建議採用手寫的xpath和cssSelector 來定位,接下來好好學習下xpath 吧
對自己來說其中使用elements是學到的一個知識點,得到一個
WebElements物件,可進行迴圈獲取,其中WebElement物件可用的方法參考:
http://www.cnblogs.com/hanxiaobei/p/6108677.html

參考網址:http://blog.csdn.net/huilan_same/article/details/52594354(動態id,class定位)
http://blog.csdn.net/huilan_same/article/details/52541680 父子、兄弟、相鄰節點定位
http://blog.csdn.net/u013840366/article/details/50188969 xpath的書寫

不會的還有好多,接著總結學習吧