:eq pseudo selector failing to function properly in Selenium WebDriver when used with Chrome

Looking to extract the first two divs of a specific class from a webpage using CSS selectors in Selenium is proving to be challenging. To illustrate this issue, let's use Stack Overflow as an example. When testing the selector in Chrome Dev Tools console, it functions correctly:

$('div.question-summary:eq(0)')
[<div class=​"question-summary narrow tagged-interesting" id=​"question-summary-27442616">​…​</div>​]
$('div.question-summary:eq(1)')
[<div class=​"question-summary narrow tagged-interesting" id=​"question-summary-27442177">​…​</div>​]

However, when attempting the same with Selenium WebDriver, an error occurs:

require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
driver.navigate.to('http://www.stackoverflow.com')
first_element = driver.find_element(:css, 'div.mainnav:eq(0)')

Selenium::WebDriver::Error::InvalidSelectorError: invalid selector: An invalid or illegal selector was specified

Is there an alternative way to define this selector? Or a method to make Selenium recognize and utilize it?

Answer №1

When working with Selenium, it's important to note that the browser's native CSS selector engine is utilized. This means that using jQuery selectors, such as :eq(0), with the find_element method may be considered invalid.

If you do need to incorporate jQuery selectors, one workaround is to manually execute the script using the execute_script method. Keep in mind that this will return an array of Selenium::WebDriver::Element, hence using .first helps retrieve the first element from the Array.

first_element = driver.execute_script('return $("div.question-summary:eq(0)");').first

In situations where you only require the use of the :eq selector, standard CSS selectors can suffice. By utilizing the find_elements and [] methods, you can achieve the same outcome:

first_element = driver.find_elements(:css, 'div.question-summary')[0]
second_element = driver.find_elements(:css, 'div.question-summary')[1]

Answer №2

To achieve a similar outcome, consider using the :nth-child selector:

first_element = driver.find_element(:css, 'div.question-summary:nth-child(0)')

It is important to understand the distinction between :eq and :nth-child

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

Guide to vertically aligning text within a row using Bootstrap 5

I am currently struggling to achieve vertical alignment of text in the center of a row. Despite my efforts, I have not been successful in achieving the desired vertical alignment. What steps can be taken to ensure that the text is vertically centered with ...

I want to use flexbox to center three divs on my webpage

I am trying to align 3 divs inside a flex container in the center of the page with equal distance between them and also from the edge of the page. .container { display : flex; width : 60%; } .para { width : 33%; padding : 1em; borde ...

section element is not receiving styles from the specified class

Whenever I want to ensure that a class is only used on specific elements, I usually prefix it with the element name. For example, using div.className limits the className styling to just div elements. However, when I tried the same approach with a section ...

Ways to access every iframe on a webpage

I am facing a challenge with a highly intricate HTML page. <html> <head></head> <body> <iframe> A </iframe> <table> <div> <span> <div> <iframe ...

Assistance needed for adjusting margins and padding within the inner content box

I'm currently in the process of designing a new website layout using CSS, but I've encountered some challenges along the way. My main goal is to ensure that all elements stay within the boundaries of the browser window, with the scroll bar appear ...

Overflow issue with floating labels in Bootstrap 5 within a grid container

Incorporated within this code snippet are floating selects placed inside a bootstrap grid: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b6bbbba0a7a0a6b5a494e1fae7fae7">[emai ...

Trigger a fixed bottom bar animation upon hover

I have a bar fixed to the bottom of the browser that I want to hide by default. When a user hovers over it, I want the bar to be displayed until they move their cursor away. <!doctype html> <html> <head> <meta charset="utf-8"> &l ...

When scrolling, a sticky table cell with a rowspan escapes the confines of the table

I am facing an issue with a table that has both a sticky header and sticky td elements with rowspan. When I scroll, the td with rowspan appears on top of its header, which in this case is the first column. Setting a z-index property puts the header on top ...

What is the best way to create a scrollable nested div?

Link to Image My goal is to keep the red section fixed while allowing only the blue section to scroll when there is overflow. The red section consists of two divs. I have attempted using position: fixed to achieve this, but encountered issues such as ove ...

Some characters are not compatible with the CSS writing-mode feature

There seems to be an issue with the CSS writing mode not applying correctly to the symbol '№'. Here is an example: <html> <head></head> <body> <p style="writing-mode: vertical-lr;"> Номер № ...

JavaScript is utilized to update HTML content through an Ajax request, but unfortunately, the styling is

Apologies for the unconventional title, I am currently in the process of creating a website. When the page is initially loaded, I call upon two scripts within the 'head' tag to create an attractive dynamic button effect. <script src="https:// ...

What is the method for initiating a radial gradient from the middle of the pie chart?

In my pie chart with grid lines, I have successfully implemented a radial gradient. However, the issue is that there is a separate gradient for each pie slice. What I really want is a single gradient originating from the center of the entire pie chart. I ...

Implementing an explicit wait in C# for a collection of WebElement using PageFactory

Is there a way to implement explicit wait using pagefactory for a group of webelements? [FindsBy(How = How.ClassName, Using = "tree-item-content")] public IList<IWebElement> TreeItems { get; set; } ...

Struggling with creating a slideshow - is the display set to none?

I've been working on a jQuery slideshow project and have encountered an issue where a hidden element is not showing up as expected. Below is the code I'm using: <section id="content"> <div id="jumbotron"> <div class="s ...

"Transcribe as HTML" for embedded IFrame components within Chrome's Inspector tool

When using Chrome's web inspector, there is a helpful "Copy as HTML" option when you right-click on a DOM element. However, it seems that this feature does not include the contents of IFrame tags, even though they are displayed in the inspector as chi ...

Tips for placing a button beside text in a modal header with bootstrap

I am working on a modal header and trying to position the "download" button next to the text "Optimize data". Despite my efforts, the button always ends up below the modal header text. I have experimented with float and align properties, but haven't b ...

Determine the type of element existing in the table cell

Currently, I am utilizing protractor to iterate through table cells in an attempt to verify the presence of a checked checkbox. var elements = element.all(by.css(columncssname)); elements.each(function (cell, index) { <--need to confirm if check ...

Having trouble establishing a connection with Firefox through Arquillian Drone

I have been referring to the documentation at this link in order to seamlessly integrate Drone into my client tests. Below is a snippet of the code I am working with: @Test @RunAsClient public void testSomething(@Drone final FirefoxDriver driver) throws ...

Capturing a screenshot with two monitors using OpenQa.Selenium will always default to the primary monitor as the reference point

In my attempt to capture a screenshot of an element, I've been using the following code as an example: var element = this.driver.FindElementByName("Example"); var sc = element.TakeScreenshot(); However, when comparing the captured scree ...

Whenever a modal is generated along with its overlay, the overlay fails to cover the entire document

With that being said, the recurring issue that always arises is as follows: -modal and overlay appears, -user scrolls down -user can click elements under the overlay How can this be fixed? The primary concern right now is with the overlay. The CSS cod ...