2017-03-06 852 views
0

我正在嘗試對可見元素進行鼠標懸停操作,然後單擊隱藏的子菜單項。 move_to_element()似乎沒有與ChromeDriver一起使用。但是,運行代碼沒有例外,只是沒有發生。python selenium:move_to_element()不起作用

我也試着在動作和webDriverWait之間嘗試sleep(),它顯示運行代碼超時。 我用python 2.7和selenium 3.0.2使用chrome 56.0。

以下是HTML代碼

<a class="dropdown-toggle" href="about-us.html" data-toggle="dropdown" role="button" aria-expanded="false"> 
About 
<i class="caret"></i> 
</a> 

<li> 
<a href="about.html">Introduction</a> 
</li> 

以下是我的測試案例的一部分

from selenium import webdriver 

from selenium.webdriver.common.action_chains import ActionChains 


    mainmenu = driver.find_element_by_xpath("path_to_about_element") 
    submenu =driver.find_element_by_xpath("path_to_introduction_element") 
    action=ActionChains(driver) 
    action.move_to_element(mainmenu)   
    action.move_to_element(submenu)   
    action.click().perform() 
+0

你能分享這些' 「path_to_about_element」'和' 「path_to_introduction_element」'? – Andersson

+0

path_to_about_element =「/ html/body/header/nav/div/div [3]/ul/li [2]/a」and path_to_introduction_element =「/ html/body/header/nav/div/div [3]/ul/li [2]/ul/li [1]/a「 –

+0

您可以使用'mainmenu = driver.find_element_by_link_text(」About「)和'submenu = driver.find_element_by_link_text(」簡介「)嗎?即使它不能解決你的問題,我建議你避免使用絕對'XPath'來定位元素 – Andersson

回答

1

嘗試下面的代碼,讓我知道結果:

from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait as wait 
from selenium.webdriver.support import expected_conditions as EC 

mainmenu = driver.find_element_by_link_text("About") 
action=ActionChains(driver) 
action.move_to_element(mainmenu).perform() 
submenu = wait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Introduction"))) 
submenu.click() 

這應該執行鼠標懸停在上元素,等到submenu元素的存在和可點擊

+0

這是'TimeoutException' –

+0

您是否確實看到'腳本執行時'頁面上出現'Introduction'元素?你可以試試'len(driver.find_elements_by_link_text(「簡介」))'? 'DOM'中可能有一些同名的隱藏鏈接... – Andersson

+0

甚至可以使用'time.sleep(10)'和'len()'返回0.只能看到一個flash。 –

0

使用下面的代碼,讓我知道,如果仍然面臨着同樣的問題:

mainmenu = driver.find_element_by_xpath("path_to_about_element") 
submenu =driver.find_element_by_xpath("path_to_introduction_element") 
action=ActionChains(driver) 
action.move_to_element(mainmenu).move_to_element(submenu).click().build().perform()  
+0

似乎我的版本的硒不支持'建立()'。獲取以下異常'AttributeError:'ActionChains'對象沒有'build'屬性 –