skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. Refer the below code:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get("https://ultimateqa.com/automation")
    
    wait = WebDriverWait(driver, 20)
    # Below line can be used to close the subscribe pop-up which appears intermittently
    # wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@class='formkit-close']"))).click()
    
    # Store parent element
    parent_element = wait.until(EC.visibility_of_element_located((By.XPATH, '//ul[@class="bottom-nav"]')))
    
    # Store all the li elements within parent element
    count = parent_element.find_elements(By.XPATH, "li")
    
    # print count of li elements
    print(len(count))
    

    Console Result:

    7
    
    Process finished with exit code 0
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search