2012-04-19 19 views
0

我想解析這個字符串出網站和識別並存儲在變量的顏色(可以說,如果其綠色分配值0,或者如果其他1)。parsin文本out.html頁面java

<tr><td class="mapbuttons" align=right> 
<a href="http://www...."><font color=green>TEXT <font color=#ff8000>(2)</font>3/14</font></a> 

我發現這個演示代碼:

import java.net.*; 
import java.io.*; 
public class WebSiteReader { 
    public static void main(String args[]){ 
     String nextLine; 
     URL url = null; 
     URLConnection urlConn = null; 
     InputStreamReader inStream = null; 
     BufferedReader buff = null; 
     try{ 
      // Create the URL obect that points 
      // at the default file index.html 
      url = new URL("http://www.yahoo.com"); 
      urlConn = url.openConnection(); 
     inStream = new InputStreamReader( 
          urlConn.getInputStream()); 
      buff= new BufferedReader(inStream); 

     // get the values I want here 

    } catch(MalformedURLException e){ 
     System.out.println("Please check the URL:" + 
              e.toString()); 
    } catch(IOException e1){ 
     System.out.println("Can't read from the Internet: "+ 
              e1.toString()); 
    } 
} 
} 

1)它是correnct?我的意思是我希望將代碼替換爲我想要的代碼,對吧? 2)你可以幫助我的代碼,因爲我是新來的Java和如何「玩」與文本?

+0

如果你要玩,使用String和模式類。這些正則表達式會變得很大而且很難看,但是它們能夠工作 - 這只是一個解決方案:) – wuppi 2012-04-19 11:11:29

回答

2

使用JSoup來完成艱苦的工作(爲您解析HTML)。解析HTML真的很難,因爲很多外面的東西都是HTML破碎的。

一種近乎以下(沒有絲毫測試應該選擇第一個字體元素,並提取顏色屬性的值。

Document doc = Jsoup.connect("http://www.yahoo.com").get(); 
Element fontTag = doc.select("font").first(); 
string theColor = fontsTag.attr("color"); 
+0

那麼從上面的評論中取代什麼呢?或在哪裏插入? – ghostrider 2012-04-19 13:52:30

+0

你應該能夠刪除上面的大部分代碼,並使用上面的代碼。 'Jsoup'處理連接到您的網站。 – 2012-04-19 14:07:18

+0

如果這段代碼不是html中的第一個字體,該怎麼辦?或者我想要多個字體? – ghostrider 2012-04-20 23:29:22