Troubleshooting issues with locating nested elements using Xpath in Selenium

Given the provided website URL and locators:

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 am seeking to determine the number of MENU_ITEMS within BOTTOM_NAV.

When utilizing nested CSS selectors, it functions correctly and retrieves the expected count of menu items, which is 7: parent_css_element.find_elements(css_element)

However, when attempting the same methodology with XPATH locators, it does not yield the desired results, showing more than 21 elements inside the parent element: parent_xpath_element.find_elements(xpath_element)

I am puzzled about why searching within nested elements works fine with CSS selectors but encounters issues with xpath locators?

Answer №1

Take a look at the code snippet provided below:

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)
# Use the line below to close the subscribe pop-up that may appear
# wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@class='formkit-close']"))).click()

# Access the parent element
parent_element = wait.until(EC.visibility_of_element_located((By.XPATH, '//ul[@class="bottom-nav"]')))

# Get all li elements within the parent element
count = parent_element.find_elements(By.XPATH, "li")

# Print the count of li elements
print(len(count))

Output in Console:

7

Process finished with exit code 0

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The event listener's handler function is failing to capture and return all attributes of the event object for a mouse click

Using C# code in a standard UnitTest project template of Visual Studio, I incorporated Selenium web driver support by adding Selenium WebDriver Support classes and Selenium WebDriver NuGet packages. The snippet below was then inserted into the Test method ...

Python Selenium not operating within a Docker environment

I am facing an issue with running a selenium parser in a docker container. The script works fine on a local machine but encounters errors when run inside the container. It seems like selenium is not functioning properly within the docker environment, as I ...

Display the output of an array in JavaScript within the same document

I am struggling to print the contents of a JavaScript array data: [ JSON.parse(genreCanvas.dataset.count).forEach(count => { `${count},\n`; }) ], to achieve the following result: data: [ 1, ...

Display scrollable content at the bottom

I am currently working on creating a chat application using JavaScript (AngularJS without jQuery) and I am wondering if it is possible to have a scrollable div load to the bottom automatically. While I am familiar with the scrollTo JS property, I do not f ...

Malfunctioning Bootstrap collapse feature

I am experiencing an issue with my modal that contains 2 blocks. When I click on the .emailInbound checkbox, it opens the .in-serv-container, but when I click on the .accordion-heading to reveal the comment section, the .in-serv-container collapses. What c ...

Issue with onClick event not triggering within echo statement when using AJAX

When inserting the following code snippet into the head section of a page: <script type="text/javascript"> function vote() { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject( ...

Tips on using soft assertions to prevent test run failures

I need to ensure that my test run continues even if one or more assertions fail in TestNG. To achieve this, I have looked into the following resources to implement soft assertion in my project: However, I am having trouble understanding the flow of code ...

Exception encountered: ElementNotVisibleException when using selenium with Firefox on an Amazon EC2 instance running xvfb-run

Currently facing this issue: I have developed a Java code using Selenium (version: 2.43.0) to automate logging into a web page without the ability to modify it, using the Firefox driver. On my Windows machine, I can successfully locate and interact with e ...

There seems to be a JSON syntax error on the website for tracking Covid-

Hi everyone, I'm currently working on a Covid-19 tracker website and facing an issue that says: 'SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data' ; Being new to web development, I am unsure about what&apo ...

The playwright instructed to capture a screenshot following each click

I am a beginner when it comes to using Playwright. I was optimistic that I could achieve my goal using page.evaluate, as in the documentation it states "page.evaluate() API can run a JavaScript function in the context of the web page and bring results back ...

The Content Security Policy is blocking other sources because it is set to 'self

Having these two inline script tags: <script async defer src="https://apis.google.com/js/api.js"></script> <script async defer src="https://accounts.google.com/gsi/client"></script> important to note: attempted ...

Issue with custom leaflet divIcon not maintaining fixed marker position during zoom levels

After creating a custom marker for leaflet maps, I noticed that it shifts position drastically when zooming in and out of the map. Despite trying to adjust anchor points and positions, the issue persists. I have provided the code below in hopes that someon ...

What is the process for clicking a button and choosing values with selenium?

When I need to make a selection on a website, I click on the "User List" button and choose from the values listed in the "li" tag. Once I click the button, the available values appear like a dropdown list. I attempted to use Selenium's dropdown optio ...

The html parser remains unchanged

Currently, I am developing a script that notifies me when there are changes on a specific webpage. To achieve this, I am utilizing bs4 and Python Selenium. However, I am encountering an issue where bs4 does not seem to retrieve the updated page source. dri ...

Implement various class versions tailored specifically for mobile browsers

While editing a Wordpress theme, I decided to include a content box within Bootstrap's <div class="well">. However, I soon encountered an issue where there was excess space in the content box on desktop view. To address this, I removed the paddi ...

Binding event listeners to dynamically created elements poses a challenge

I am facing difficulty in adding an event listener to dynamically created elements. The issue lies in my code where I am unable to detect the insertion of <p> element resulting in the lack of console message Bar Inserted. Could you point out if there ...

Material UI - Panel Expansion does not cause the div above to resize

Scenario : Utilizing leaflet and React-table together in one component. Two divs stacked vertically - one containing a leaflet map and the other a react-table. The second div has Expansion Panels with react-table inside. Issue : Problem arises when ...

Chromedriver 80 causing StaleElementReferenceException with Selenium

After the Chromedriver 80 update, the following code that used to work is now causing a StaleElementReferenceException when the element is present in the DOM: public static void WaitUntilElementNotExists(string clase) { Instance.Manage().Timeouts(). ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

Creating a customized file input using CSS

I am currently utilizing Bootstrap4 to craft my webpage and I am incorporating a custom file input bar. To retrieve the three labels of the input bar ("Choose file", "Browse", "Upload") from my stylesheet, I have created three custom classes with their co ...