5

I want to avoid using XPath where possible when finding elements in webdriver, but be able to reference child elements from already found elements e.g.

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 up into the table element and the rows, without having to refer back to the table expression. e.g. for XPath:

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

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

I've 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 error `assert_ok': An invalid or illegal string was specified (Selenium::WebDriver::Error::UnknownError)

Removing the first '>' of course works, however means decendant tbody's are selected and not just immediate children.

How can I do this correctly using just css?

4

1 回答 1

5

由于您没有提供页面网址,因此我采用了这种中文。现在我试图找出第一个具有classname的表的第二行的表列值"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ǔ"

你尝试的方式table.find_elements(:css, '> tbody > tr')不是有效的css语法。selenium-webdriver应该是table.find_elements(:css, 'tbody > tr')。我建议你这样写:

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

jsfiddle

table = driver.find_element(:css, 'div#myelement table.myclass')
rows = table.find_elements(:css, 'tbody:nth-of-type(1) > tr')
于 2013-08-25T14:31:35.993 回答