2017-07-24 27 views
0

這是我的表:我怎樣才能Watir刮從我的Rails應用程序中的實例變量從這個表中的值?

<tbody><tr> 
        <td class="rhs">Number:</td> 
        <td id="number"><strong>2</strong></td> 
     </tr> 
     <tr> 
        <td class="rhs">Total:</td> 
        <td id="total"><strong>£60,000</strong></td>   
     </tr> 
     <tr> 
        <td class="rhs">GrandTotal</td> 
        <td><strong>£200,000</strong></td>   
     </tr> 
     <tr> 
        <td class="rhs">Limit:</td> 
        <td><strong>£550,000</strong></td>   
     </tr> 
     <tr> 
        <td class="rhs">Frequency:</td> 
        <td><strong>Annually</strong></td> 
     </tr> 
     <tr> 
         <td class="rhs">Percentage:</td> 
         <td><strong>0%</strong></td> 
     </tr> 
     <tr class="display-total"> 
         <td class="rhs">Year 1:</td> 
         <td><strong>£480.00</strong></td> 
     </tr>   
</tbody></table> 

而且我用的Watir試圖「刮」的值,並將其存儲在我的應用程序變量。

def scrape_quote 
     puts @quote.number = @browser.td(:id, 'number').text 
     @quote.total = @browser.td(:id, 'total').text 
     @quote.grand_total= @browser.tr(:index => '3').td(:index => '1').text 
     @quote.limit = @browser.tr(:index => '4').td(:index => '1').text 
     @quote.frequency = @browser.tr(:index => '5').td(:index => '1').text 
     @quote.percentage = @browser.tr(:index => '6').td(:index => '1').text 
     @quote.yr1 = @browser.tr(:index => '7').td(:index => '1').text 

     puts @quote.number + ' ' + @quote.total + ' ' + @quote.grand_total 
     + ' ' + @quote.limit + ' ' + @quote.frequency + ' ' + @quote.commission 
      + ' ' + @quote.yr1 
end 

(只是puts'd看方法是否工作過或沒有,一旦工作我會真正保存它們的型號。)

不幸的是,上面沒有捕捉和或保存那些值如預期。你能幫我看看我的方式錯誤嗎?

謝謝。

+0

它會幫助你,如果你澄清到底輸出是什麼。至少,'tr'元素的':index'看起來要偏離一個。在將它們存儲在'@ quote'之前,你還應該驗證輸出 - 也就是與Watir的交互或與'@ quote'交互的問題。 –

回答

0

您嘗試使用字符串訪問索引值的值,該值應該是整數。在任何情況下,最終的代碼應該是這樣的:

rows = @b.trs #Retrieve all trs 
scraped_values = {} #Creating a dictionary to store scraped values 

for row in rows #iterate over trs 
    scraped_values[row[1].id] = row[1].text #retrieve the data 
end 
puts scraped_values 
0

在的Watir,將秒的元素標籤後,得到所有包含該標籤的元素,並把它的陣列上。

所以在你的情況下,如果你把命令@browser.trs.length的值將是7,因爲你的表中有7行。

至於身份證,我總是使用@browser.td(:id=>'id')它始終有效,但@browser.td(:id, 'id')也適用於我。

def scrape_quote 
     puts @quote.number = @browser.td(:id=>'number').text 
     @quote.total = @browser.td(:id=>'total').text 
     @quote.grand_total= @browser.trs[3].tds[1].text 
     @quote.limit = @browser.trs[4].tds[1].text 
     @quote.frequency = @browser.trs[5].tds[1].text 
     @quote.percentage = @browser.trs[6].tds[1].text 
     @quote.yr1 = @browser.trs[7].tds[1].text 

     puts @quote.number + ' ' + @quote.total + ' ' + @quote.grand_total 
     + ' ' + @quote.limit + ' ' + @quote.frequency + ' ' + @quote.commission 
      + ' ' + @quote.yr1 
end