Daniel
Daniel

Reputation: 2469

Python Selenium to select "menuitem" from "menubar"

I have a code that clicks a button on a web page, which pops up a menubar. I would like to select a menuitem from the choices that appear, and then click the menuitem (if possible); however, I'm at a roadblock.

Here is the relevant part of the code so far:

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()

Here is the error it's throwing, based on what I have written:

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

Note: it appears that the id for this element changes each time the page loads (which is probably the cause of the error). I've tried searching for the element by find_element_by_class_name as well, but it has a compound class name and I keep getting an error there, too.

Here's the code of the menubar:

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

and the menuitem I want:

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

I'm looking for a way to select the menuitem. Thanks!

Upvotes: 1

Views: 2817

Answers (2)

Subh
Subh

Reputation: 4424

Try this xpath

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

It will check for the 'div' element having attribute 'role' as 'menuitem' and having exact text as 'text'.

Say, there is a menuitem "Lamborghini AvenTaDor" under your menu. So, the code for that will become:

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

Upvotes: 2

alecxe
alecxe

Reputation: 474161

You can find the element by xpath and check that the id attribute starts with gwt-uid-:

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

You can also apply additional checks if needed, e.g. check role attribute as well:

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

Upvotes: 0

Related Questions