Leveraging the css child selector within Ruby's Selenium-Webdriver to locate multiple elements

I prefer to minimize the usage of XPath in webdriver when locating elements, but still want the ability to access child elements from previously identified ones. For example:

Consider the following HTML structure:

<div id="myelement">
    <table class="myclass">
       <tbody>
           <tr>
               <td>something</td>
               <td>
                   <table>
                       <tbody>
                           ...
                       </tbody>
                   </table>
               </td>
           </tr>
           <tr>
               ...
           </tr>
       </tbody>
    </table>
</div>

If I have a CSS selector like this:

driver.find_elements('div#myelement table.myclass > tbody > tr')

I want to separate this into finding the table element and the rows without having to refer back to the entire table expression. This is achievable with XPath like so:

table = driver.find_element(:xpath, "//div[@id='myelement']//table[@classname='myclass']")

rows = table.find_elements(:xpath, 'tbody/tr')

Attempting to do the same with CSS like using JQuery $('div#myelement table.myclass').find('> tbody > tr') led to an error: `assert_ok': An invalid or illegal string was specified (Selenium::WebDriver::Error::UnknownError)

Although removing the first '>' would work, it does not limit the selection to immediate children. So, how can I achieve this correctly using only CSS?

Answer №1

Without providing the page URL, I decided to use information from the Chinese language page. My aim was to retrieve the values in the table columns for the second row of the first table with the class name "wikitable sortable."

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.navigate.to "http://en.wikipedia.org/wiki/Chinese_language"

table = driver.find_element(:css,"table.wikitable") # !> assigned but unused variable - table
tb_col = driver.find_elements(:css,"tr:nth-of-type(2)>td")
tb_col[0..5].each{|e| p e.text}
# >> "汉语/漢語 or 中文\nHànyǔ or Zhōngwén"
# >> "汉语"
# >> "中文"
# >> "Wu\nNotes: includes Shanghainese"
# >> "Wu; 吴/吳"
# >> "Wúyǔ"

Your attempt at using

table.find_elements(:css, '> tbody > tr')
is not valid CSS syntax in selenium-webdriver. It should actually be
table.find_elements(:css, 'tbody > tr')
. Here's a suggestion on how you can improve your code:

table = driver.find_element(:css, 'div#myelement table.myclass>tbody')
rows = table.find_elements(:css, 'tr')

You can also refer to this jsfiddle example.

table = driver.find_element(:css, 'div#myelement table.myclass')
rows = table.find_elements(:css, 'tbody:nth-of-type(1) > tr')

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

Selenium in Python fails to execute the clicking action

My mind is spinning with frustration. I am trying to click on a specific button, but an unknown error keeps popping up: Traceback (most recent call last): File "C:\Users\leosc\PycharmProjects\ogameBot\guideline.py", line 22, i ...

Styling Dropdown Options Based on Conditions in React

In my current project, I am attempting to modify the className of selected items within a mapped array using another array (this.props.notPressAble). The reason for this is because I want certain objects in the array to have a different CSS style. handleOp ...

The arrangement vanishes when using identical html/css coding

When using the same HTML/CSS coding, the layout disappears and appears misaligned on one page but works perfectly on another. The issue seems to be that the first section of the main area is getting a width of 938px instead of 5px. I've tried adding w ...

When using Selenium WebDriver with Firefox to submit forms, if the window is positioned behind another window, the result may be empty

When I visit the website "uk.burberry.com", I notice that there is a search field at the top along with a search button to look for items. Interestingly, when I perform a search with just one Firefox window open, everything works smoothly. However, if I ha ...

The importance of white space within email design utilizing table tags in HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html style="opacity: 1;" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv ...

Ways to dynamically incorporate media queries into an HTML element

Looking to make some elements on a website more flexible with media rules. I want a toolbar to open when clicking an element, allowing me to change CSS styles for specific media rules. Initially thought about using inline style, but it turns out media rul ...

Why do I see my footer displayed twice on the page?

<div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li> @Ajax.ActionLink("Imagenes List", "Images", "Home", new { page = 0 }, new AjaxOptions() ...

Preserving Dimension Ratio with Full Width and Height (Trimming Overflow in CSS)

I'm currently developing a full-screen background slideshow. My query is: How can I ensure that an image fills the entire screen while maintaining its aspect ratio? Although min-height and min-width provide some assistance, they do not maintain the ...

The functionality of the Escape key is not supported in Selenium WebDriver when using Python

Attempting to create a page scraper that pauses loading the page every 2 seconds. Trying to simulate pressing the ESCAPE key using action chains but it doesn't seem to work. No errors show up, yet nothing happens. Code below is an excerpt where I atte ...

What could be the reason why the @media print selector is not showing the correct format when I try to print?

When I click the print button, the text is supposed to display in four columns in the print dialog, but it appears as paragraphs instead. This is my script code where there is a click event for the print button. When I click on it, the print dialog pop ...

Updating selenium element using Java language

Currently, I am in the process of creating an automated bot that is able to extract data from a specific website. While the bot successfully reads the data as expected, I encountered the need to implement intervals using Timers. To achieve this, I created ...

Finding and removing a specific CSS pattern from a webpage that has been loaded

Encountered a troublesome Amazon.com page that appears blank in print preview, specifically the Online Return Center\Your Return Summary page. After much troubleshooting on a locally saved copy of the webpage, I pinpointed the issue to a problematic l ...

Why Changing the Width of a Flexbox Container Doesn't Impact Its Children?

Attempting to use TweenLite to animate the width of the blue sidebar down to zero, however facing an issue where the content breaks outside the parent's bounds. https://i.stack.imgur.com/4rEVr.png It is unusual for this to happen with Flexbox, given ...

My goal is to overlay an information box on top of an image while ensuring that both elements remain contained within the designated area

I've experimented with different approaches, such as using position absolute on one element and position relative on the other. However, I always face issues where one overflows, despite setting overflow to hidden. Below is my current code snippet. (P ...

Looking to incorporate nested rules in `JSS` using `CSS`?

Can someone guide me on how to use CSS class-nesting in Material-UI or JSS in general? I have been attempting the following: card: { cardHeader:{ marginTop:"30px" } } ...

Transform your ordinary HTML select into a stylish span with this custom CSS class

I need help making a select element appear like a span under certain conditions. The CSS class I currently have works with input boxes, but not with dropdowns. Is there any advice on how to style the select element to look like a span without actually repl ...

Tips for Implementing Authentication in Rest Assured

Struggling to Authenticate the API with Rest Assured? Does anyone have an example of authenticating and authorizing an API using Rest Assured? ...

jQuery Mobile - Implementing Persistent Toolbars along with a custom back button functionality

UPDATE Here is a fiddle of the problem: https://jsfiddle.net/9k449qs2/ - attempt to select the header using your picker, but every time you click it will select the whole page instead. I am currently working on a project that includes a persistent header ...

Determine the frequency of a word in Java programming language

Ticket Type Priority Assigned Incident 3 - Medium Acknowledgement Service Request 3 - Medium Assigned Problem 2 - High Assigned Incident 3 - Medium Assigned Service Request 3 - Medium Closed Incident 3 - Medium Assigned Service ...

What is the best way to add a border around an image along with a button using VueJS?

I am struggling to link a button and an image in VueJS to display a border around the picture. While I can successfully display the border on the button, I am unsure how to extend it to the image as well. Vue.component('my-button', 'my-img& ...