Return boolean for navigation (nav) links before and after clicking them I want to write a function to check if some nav links exist or not. However, those nav links are under one of the listbox icons so I need to click the icon
before and after to check if the element exists. The following code works. Nonetheless, is there a better way for writing this?

def func(locator, name):
    if self.driver.find_element_by_xpath('{}{}/i'.format(locator, '[@aria-expand="false"]')):
        self.driver.find_element_by_xpath(locator).click()
    try:
        est = True
        self.driver.find_element_by_xpath('{}//a[text()="{}"]'.format(locator, name)).
    except NoSuchElementException:
        est = False
    if self.driver.find_element_by_xpath('{}{}/i'.format(locator, '[@aria-expand="true"]')):
        self.driver.find_element_by_xpath(locator).click()

    return est
You don't have to construct XPath expressions via string formatting at all. You can locate the element and then find an inner child element by calling the find_element_by_*() methods on a parent element, making the search "context-specific".

And, there is a better locator to find the links by text - "by link text".

Also, to check if the nav listbox is expanded or not, you can use .get_attribute() method to extract and check the value of the aria-expand attribute.

Improved code:

def func(locator, name):
    navigation_box = self.driver.find_element_by_xpath(locator)

    # expand the listbox if not expanded
    is_expanded = navigation_box.get_attribute("aria-expand") == 'true'
    if not is_expanded:
       navigation_box.click()
       is_expanded = True

    link_exists = len(navigation_box.find_elements_by_link_text(name)) &gt; 0

    # collapse the listbox if expanded
    if is_expanded:
        navigation_box.click()

    return link_exists


You should additionally think of a better name for the function and add a docstring explaining what the function does.