2015-11-03 102 views
1

我试图提取的价值“上一个关闭”从finance.yahoo.com/q?s=[Symbol]如何在Android中使用Jsoup从嵌套div中提取表数据?

下面是HTML是什么样子,

<div class="yui-u first yfi-start-content"> 
    <div class="yfi_quote_summary"> 
    <div id="yfi_quote_summary_data" class="rtq_table"> 
    <table id="table1"> 
    <tbody> 
     <tr> 
     <th scope="row" width="48%">Prev Close:</th> 
     <td class="yfnc_tabledata1">208.25</td> 
     </tr> 
     <tr> 
     <th scope="row" width="48%">Open:</th> 
     <td class="yfnc_tabledata1">211.00</td> 
     </tr> 
     <tr> 
     <th scope="row" width="48%">Bid:</th> 
     <td class="yfnc_tabledata1">N/A</td> 
     </tr>  
    </tbody> 
    </table> 
    </div> 
    </div> 

这里是如何我试图提取所需的数据。

Document doc = Jsoup.connect("http://finance.yahoo.com/q?s=goog").get(); 
Elements e = doc.select("td.yfnc_tabledata1"); 
String close = e.get(0).text(); 

但是,这给出了一个IndexOutOfBoundsException,表明ArrayList的大小是0,因此e不能返回一个元素。

我在做什么错?

+1

我试过了。有用。无论如何,将'useragent'和'referrer'添加到标题中。 – Hasanaga

+0

工作,非常感谢你! –

+0

祝你好运。我添加为答案。如果我的回答对您有帮助,请考虑将其提升并接受为正确答案。 – Hasanaga

回答

0

在访问Elements之前,请确保它不是空的。这样,你可以避免IndexOutOfBoundsException。另外,如@Hasanaga提到它,您应该设置userAgentreferrer标题。

Document doc = Jsoup 
    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6") // 
    .referrer("http://finance.yahoo.com") // 
    .connect("http://finance.yahoo.com/q?s=goog") // 
    .get(); 

Elements e = doc.select("td.yfnc_tabledata1"); 
if (e.isEmpty()) { 
    throw new RuntimeException("Unable to locate table cell."); 
} 

String close = e.get(0).text();