# 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):

# expand the listbox if not expanded
if not is_expanded: