given the following site and locators:
https://ultimateqa.com/automation
XPATH
CONTAINER = (By.XPATH, '//ul[@class="bottom-nav"]')
MENU = (By.XPATH, '//li[contains(@class, "menu-item")]')
CSS
BOTTOM_NAV = (By.CSS_SELECTOR, '.bottom-nav')
MENU_ITEM = (By.CSS_SELECTOR, '.menu-item')
I need to find inside the BOTTOM_NAV the number of MENU_ITEMS.
When using nested CSS it is working correctly and returns expected number of menu items which is 7: parent_css_element.find_elements(css_element)
When trying the same but with XPATH locators then it is not working and elements inside the parent element are a lot more 21 and more: parent_xpath_element.find_elements(xpath_element)
I am trying to figure out why searching in nested element is not working with xpath locators but working correctly with css selectors?
2
Answers
The difference in behavior between CSS selectors and XPath locators when searching within nested elements could be due to how they handle the search context. CSS selectors naturally maintain the context within the nested element, while XPath locators may require specifying the context explicitly using a dot (.) at the beginning of the XPath expression. Adding the dot (.) ensures that XPath locators search within the specific parent element.
Best Regards
Refer the below code:
Console Result: