ruby – 如何使用Capybara获取HTML表格行

前端之家收集整理的这篇文章主要介绍了ruby – 如何使用Capybara获取HTML表格行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用部分href xpath扫描 HTML表中的行,并使用该行的其他列值执行进一步的测试.
<div id = "blah">
  <table>
    <tr>
      <td><a href="afile?key=HONDA">link</a></td>
      <td>29 33 485</td>
      <td>45.2934,00 EUR</td>
    </tr>
    <tr>
      <td><a href="afile?key=HONDA">link</a></td>
      <td>22 93 485</td>
      <td>38.336.934,123 EUR</td>
    </tr>
    <tr>
      <td><a href="afile?key=something_else">link</a></td>
      <td>394 27 3844</td>
      <td>3.485,2839 EUR</td>
    </tr>    
  </table>
  </div>

在cucumber-jvm步骤定义中,我很容易像下面那样执行它(我使用Ruby更舒服)

@Given("^if there are...$")
public void if_there_are...() throws Throwable {
            ...
            ...
           baseTable = driver.findElement(By.id("blah"));
           tblRows = baseTable.findElements(By.tagName("tr"));

        for(WebElement row : tblRows) {                                                 
            if (row.findElements(By.xpath(".//a[contains(@href,'key=HONDA')]")).size() > 0) {
                List<WebElement> col = row.findElements(By.tagName("td")); 
                tblData dummyThing = new tblData();
                dummyThing.col1 = col.get(0).getText();
                dummyThing.col2 = col.get(1).getText();
                dummyThing.col3 = col.get(2).getText();
                dummyThing.col4 = col.get(3).getText();
                dummyThings.add(dummyThing);
            }
        }

我在这里很无能为力

page.find('#blah').all('tr').each { |row|
  # if row matches xpath then grab that complete row
  # so that other column values can be verified
  # I am clueless from here
  row.find('td').each do { |c|

  }
  page.find('#blah').all('tr').find(:xpath,".//a[contains(@href,'key=HONDA')]").each { |r|
    #we got the row that matches xpath,let us do something
  }
}

解决方法

我想你想做的事情:
page.all('#blah tr').each do |tr|
  next unless tr.has_selector?('a[href*="HONDA"]')

  # Do stuff with trs that meet the href requirement
  puts tr.text
end
#=> link 29 33 485 45.2934,00 EUR
#=> link 22 93 485 38.336.934,123 EUR

这基本上说:

>使用id’blah’查找元素中的所有trs
>迭代每个trs
>如果tr没有包含HONDA的href的链接,请忽略它
>否则,输出行的文本(符合条件).你可以在这里做任何你需要的东西.

您还可以使用xpath将上述内容折叠为单个语句.但是,我不认为它是可读的:

page.all(:xpath,'//div[@id="blah"]//tr[.//a[contains(@href,"HONDA")]]').each do |tr|
  # Do stuff with trs that meet the href requirement
  puts tr.text
end
#=> link 29 33 485 45.2934,123 EUR

以下是如何检查每个匹配行的链接URL和列值的示例:

page.all('#blah tr').each do |tr|
  next unless tr.has_selector?('a[href*="HONDA"]')

  # Do stuff with trs that meet the href requirement
  href = tr.find('a')['href']
  column_value_1 = tr.all('td')[1].text
  column_value_2 = tr.all('td')[2].text

  puts href,column_value_1,column_value_2
end
#=> file:///C:/Scripts/Misc/Programming/Capybara/afile?key=HONDA
#=> 29 33 485
#=> 45.2934,00 EUR
#=> file:///C:/Scripts/Misc/Programming/Capybara/afile?key=HONDA
#=> 22 93 485
#=> 38.336.934,123 EUR

猜你在找的Ruby相关文章