2014-11-08 209 views
1

我有一個代碼,點擊網頁上的一個按鈕,彈出一個menubar。我想從出現的選項中選擇一個menuitem,然後clickmenuitem(如果可能);然而,我在路障。Python Selenium從「menubar」中選擇「menuitem」

這裏是代碼的相關部分迄今:

from selenium import webdriver 
driver = webdriver.Chrome() 
driver.get('URL') 

Btn = driver.find_element_by_id('gwt-debug-BragBar-otherDropDown') 
Btn.click() #this works just fine 

MenuItem = driver.find_element_by_id('gwt-uid-463') #I'm stuck on this line 
MenuItem.click() 

這裏是它的基礎是什麼我寫拋出的錯誤:

raise exception_class(message, screen, stacktrace) 
selenium.common.exceptions.NoSuchElementException: Message: no such element 

注:看來該id因爲這個元素每次頁面加載都會改變(這可能是錯誤的原因)。我試着搜索find_element_by_class_name,但它有一個複合類名稱,我也一直在那裏得到一個錯誤。

這裏是menubar的代碼:

<div class="gux-combo gux-dropdown-c" role="menubar" id="gwt-debug-BragBar-otherMenu"> 

menuitem我想:

<div class="gux-combo-item gux-combo-item-has-child" id="gwt-uid-591" role="menuitem" aria-haspopup="true">text</div> 

我正在尋找一種方式來選擇menuitem。謝謝!

回答

0

您可以find the element by xpath,檢查id屬性開始與gwt-uid-

menu_item = driver.find_element_by_xpath('//div[starts-with(@id, "gwt-uid-")]') 
menu_item.click() 

您還可以申請額外的檢查,如果需要的話,例如檢查role屬性,以及:

driver.find_element_by_xpath('//div[starts-with(@id, "gwt-uid-") and @role="menuitem"]') 
+0

感謝您的快速回答,@alecxe!試過了,它完美地完成了這項工作。 – Daniel 2014-11-11 04:45:30

2

試試這個XPath

driver.find_element_by_xpath('//div[@role='menuitem' and .='text']').click(); 

它會檢查「DIV」元素具有與「菜單項」,並且具有精確的文本爲「文本」屬性「角色」 。

說,菜單下有一個菜單項「Lamborghini AvenTaDor」。因此,代碼將變爲:

driver.find_element_by_xpath('//div[@role='menuitem' and .='Lamborghini AvenTaDor']').click(); 
+0

+1這個想法,@Subh!這將對我今後的編碼工作有所幫助。 – Daniel 2014-11-11 04:45:00

相關問題