2015-06-22 20 views
0

我想從HTML源代碼中提取一些數據到我的Java項目。 html取自「必應搜索圖片」,我想從<a>標籤獲取所有圖片。這是html代碼:如何從HTML中提取多個值到java?

<a href="/images/search?q=nba&amp;view=detailv2&amp;&amp;&amp; 
id=FE19E7BB2916CE8B6CD78148F3BC0656D151049A&amp; 
selectedIndex=3&amp; 
ccid=2%2f7OBkGc&amp; 
simid=608035681734625885&amp; 
thid=JN.tdPCsRj4HyJzbwA%2bgXsS8g" 
ihk="JN.tdPCsRj4HyJzbwA+gXsS8g" 
m="{ns:&quot;images&quot;,k:&quot;5070&quot;,dirovr:&quot;ltr&quot;, 
mid:&quot;FE19E7BB2916CE8B6CD78148F3BC0656D151049A&quot;, 
surl:&quot;http://www.nba.com/gallery/rookie/070727_1.html&quot;, 
imgurl:&quot;http://www.nba.com/media/draft_class_3_07_070727.jpg 
&quot;, 
ow:&quot;300&quot;,docid:&quot;608035681734625885&quot;,oh:&quot;192&quot;,tft:&quot;58&quot;}" 
mid="FE19E7BB2916CE8B6CD78148F3BC0656D151049A" 
t1="The 2007 NBA Draft Class" 
t2="625 x 400 · 374 kB · jpeg" 
t3="www.nba.com/gallery/rookie/070727_1.html" 
h="ID=images,5070.1"><img data-bm="16" 
src="https://tse3.mm.bing.net/th?id=JN.tdPCsRj4HyJzbwA%2bgXsS8g&amp;w=217&amp;h=142&amp;c=7&amp;rs=1&amp;qlt=90&amp;o=4&amp;pid=1.1" 
style="width:217px;height:142px;" width="217" height="142"> 
</a> 

,這是我如何試圖提取它,但沒有成功:

public static void main(String[] args) { 

     String title = "dog"; 
     String url = "https://www.bing.com/images/search?q="+title+"&FORM=HDRSC2"; 
     try { 
      Document doc = Jsoup.connect(url).get(); 
      Elements img = doc.getElementsByTag("a"); 

      for (Element el : img) { 
       String src1 = el.absUrl("imgurl"); 
       String src2 = el.absUrl("surl"); 
       System.out.println(src1 + " " + src2);  
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 

,如果有可能的任何想法?

+0

在哪一點你沒有成功? 'Jsonp.connect'或者'for loop'裏面?要麼 ? – pmverma

+0

連接工作正常,但沒有結果'String src1 = el.absUrl(「imgurl」); String src2 = el.absUrl(「surl」);' –

+0

您是否在使用任何IDE進行開發?如果是這樣,請嘗試調試並找到正確的表達式。 – pmverma

回答

1

據我理解你的<a>元素有屬性m,不imgurlsurl,並m包含一個JSON又包含imgurlsurl。所以,你應該從m提取JSON:

String m = el.attr("m"); 

然後解析m作爲JSON,使用任何你喜歡的庫,例如GSON

class MJson { 
    private String imgurl; 
    private String surl; 

    ... 
} 

MJson mJson = new Gson().fromJson(m, MJson.class); 
String src1 = mJson.getImgurl(); 
String src2 = mJson.getSurl(); 
+0

哇謝謝!但我需要寫什麼insted'''請 –

+0

@mattmatt獲取和設置器 – user3707125

+0

我仍然得到'@ null' –