2013-05-10 4 views
2

ruby, watir 및 정규 표현식을 사용하여 HTML 테이블 (아래)에서 값을 파싱하려고합니다. 테이블 행에 지정된 값이있는 경우 앵커 태그에서 ID 정보를 구문 분석하고 싶습니다. 예를 들어 Event1, Action2가 대상 행 선택 항목 인 경우 내 목표는 테이블 행에 대해 "edit_ #"을 얻는 것입니다. 정말 작동하지 않습니다 다음을 시도Ruby - 테이블 값 추출

<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> 

: HTML의

Table: 
Event1 | Action2 
Event2 | Action3 
Event3 | Action4 

예제 (이 작업 코드이기 때문에 내가 잘하면 당신은 아이디어를 얻을, 약간의 정보를 잘라했습니다)

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)

나는 루비와 와트가 상당히 새롭기 때문에 도움이된다. 이 같은

답변

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의 모든 셀을 반복하는 방법은 무엇입니까? 나는 루비를 처음 사용하고 있으며 문서를 읽는 방법을 아는 데 어려움을 겪고 있습니다. – stack1

1

이것은 젤코 응답에 대한 대안입니다. 일치하는 행이 하나만 있다고 가정하면 each 대신 find을 사용하여 첫 번째 일치 항목이 발견 될 때까지 (모든 행을 항상 거치지 않고) 행을 반복합니다.

#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