2013-05-10 61 views
2

我想使用ruby,watir和正則表達式從HTML表格(下面)解析值。如果錶行具有指定的值,我想解析來自錨標記的id信息。例如,如果Event1,Action2是我的目標行選擇,那麼我的目標是獲取表格行的「edit_#」。 HTML的紅寶石 - 提取表值

Table: 
Event1 | Action2 
Event2 | Action3 
Event3 | Action4 

實例(我剪了一些信息出來,因爲這是工作代碼,希望你的想法):

<div id="table1"> 
    <table class="table1" cellspacing="0"> 
    <tbody> 
     <tr> 
     <tr class="normal"> 
      <td>Event1</td> 
      <td>Action2</td> 
      <td> 
      <a id="edit_3162" blah blah blah… > 
      </a> 
      </td> 
    </tr> 
     <tr class="alt"> 
      <td> Event2</td> 
      <td>Action3 </td> 
      <td> 
      <a id="edit_3163" " blah blah blah…> 
      </a> 
      </td> 
     </tr> 
    </tbody> 
</table> 
</div> 

我已經試過這並沒有真正的工作如下:

wb=Watir::Browser.new 
wb.goto "myURLtoSomepage" 
event = "Event1" 
action = "Action2" 
table = browser.div(:id, "table1") 
policy_row = table.trs(:text, /#{event}#{action/) 
puts policy_row 
policy_id = policy_row.html.match(/edit_(\d*)/)[1] 
puts policy_id 

這導致該錯誤被指向policy_id = ... 行:undefined method 'html' for #<Watir::TableRowCollection:0x000000029478f0> (NoMethodError)

任何幫助表示讚賞,因爲我對ruby和watir相當陌生。

回答

3

像這樣的東西應該工作:

browser.table.trs.each do |tr| 
    p tr.a.id if tr.td(:index => 0) == "Event1" and tr.td(:index => 1) == "Action2" 
end 
+0

如何遍歷錶行或tr的所有單元格?我對ruby很陌生,而且我很難知道如何閱讀文檔。 – stack1 2015-01-22 22:09:39

1

這是澤利科答案的替代品。假設只有一行匹配,則可以使用find而不是each來遍歷行,直到找到第一個匹配(而不是始終遍歷每行)。

#The table you want to work with 
table = wb.div(:id => 'table1').table 

#Find the row with the link based on its tds 
matching_row = table.rows.find{ |tr| tr.td(:index => 0).text == "Event1" and tr.td(:index => 1).text == "Action2" } 

#Get the id of the link in the row 
matching_row.a.id