Using child css selector in ruby ​​element selenium-webdriver find_elements

I want to avoid using XPath, where possible, when searching for elements in webdriver, but to be able to refer to child elements from already found elements, for example.

For the following html:

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

I have a css expression:

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

I want to break this down into a table and row element, without referring to the table expression. for example for XPath:

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

I tried the following, which works using jQuery $ ('div # myelement table.myclass'). find ('> tbody> tr')

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

This causes an `assert_ok 'error: an invalid or illegal string is specified (Selenium :: WebDriver :: Error :: UnknownError)

Removing the first ">", of course, works, however, it means that a selective tbody is selected, and not just the nearest children.

How can I do this correctly using only css?

+4
source share
1 answer

Since you do not provide the URL of the page, I took this Chinese language . Now I tried to figure out the table column values ​​for the second row of the first table has a class name of "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ǔ" 

The way you tried table.find_elements(:css, '> tbody > tr') is invalid css syntax in selenium-webdriver . It should be table.find_elements(:css, 'tbody > tr') . I would suggest you write like this:

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

or jsfiddle

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

Source: https://habr.com/ru/post/1498833/


All Articles