2012-12-24 125 views
1

獲得TD的文本我有休耕代碼:廣東話通過指數

<table id="table1" class="class1"> 
    <thead>...<thead> 
    <tbody> 
     <tr id="1"> 
      <td class>cell1</td> 
      <td class>cell2</td> 
      <td class>cell3</td> 
      <td class>cell4</td> 
     </tr> 
     <tr id="2"> 
      .... 
     <\tr> 
     ... 

我需要去了所有的行,並檢查電池3號有「小區3」爲文本。 (對於初學者) 再經過香港專業教育學院發現,我需要繼續檢查該行的細胞數量不同的字符串3

我已經試過:

string="cell3" 
rows=browser.table.rows 
rows.each {|tr| 
    if tr.td(:index =>2).text ==string 
     puts " Found #{string}" 
     string="cellK" 
    end 
} 

Im做它在一個循環中,因爲有我需要找到幾個字符串。

但即時得到休耕錯誤:

unable to locate element, using {:index=>2, :tag_name=>"td"} 

有什麼建議? 如何獲取td的文本? 以及爲什麼我不能通過索引找到td?

+2

你確定每行有相同數量的tds(即'''tr.td(index:2).exists?'''總是返回true。我剛剛在本地嘗試過你的代碼,它工作正常見https://gist.github.com/4369348 – p0deje

回答

4

我猜測問題是thead中的標題行。表頭可能是這樣的:

<thead> 
    <tr id="0"> 
     <th class>heading1</th> 
     <th class>heading2</th> 
     <th class>heading3</th> 
     <th class>heading4</th> 
    </tr> 
<thead> 

請注意,有一個tr。因此,table.rows將包括標題行。另請注意,它使用的是th而不是td單元。 watir可能在這裏找不到索引爲2的td,因爲在這一行中根本沒有tds。

假設這是問題,你有幾個解決方案。

解決方案1 ​​ - 讓th和td相當於用細胞

在循環中,使用cell代替td

rows.each {|tr| 
    if tr.cell(:index =>2).text == string #Note the change here 
     puts " Found #{string}" 
     string="cellK" 
    end 
} 

Table#cell比賽tdth細胞。這意味着cell(:index, 2)將匹配行中的第3個tdth。當watir檢查標題行時,它現在將找到一個值。

解決方案2 - 忽略THEAD

當得到的行進行檢查,限制rows集合只包括在TBODY行:

rows = browser.table.tbody.rows 

這則忽略的riws那是造成問題的原因。

+1

這就是問題所在,謝謝! – MichaelR