2014-02-24 40 views
0

以下代碼可以幫助我從提供的URL獲取源代碼而不會出現任何錯誤。但是我正在尋找的是格式化我收到的源代碼。如何在java中設置網頁源代碼的格式?

我的手動任務前面是去這個網站http://www.freeformatter.com/html-formatter.html貼我的源代碼,然後通過選擇每縮進選項3空間格式化。我如何讓我的java代碼爲我做相同的格式?

我想它格式化的原因是因爲我還有一個腳本,由線讀取該行並保存所需要的數據,忽略其餘部分。

private static String getUrlSource(String url) throws IOException { 
    URL x= new URL(url); 
    URLConnection yc = x.openConnection(); 
    BufferedReader in = new BufferedReader(new InputStreamReader(
      yc.getInputStream(), "UTF-8")); 
    String inputLine; 
    StringBuilder a = new StringBuilder(); 
    while ((inputLine = in.readLine()) != null) 
    { a.append(inputLine); a.append("\n"); 
    } 
    in.close(); 

    return a.toString(); 
} 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    System.out.println("Hello"); 

    url="http://www.bctransit.com/regions/cfv/schedules/schedule.cfm?p=day.text&route=1%3A0&day=1&"; 

    try { 
    String value= getUrlSource(url); 
    System.out.println(value); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

回答

2

如果您要抓取網頁,我建議您改用真正的HTML解析器。你的方法遲早會失敗。

我會建議在看看jsoup。雖然我從來沒有使用過它,但我的Python對手Beautifulsoup獲得了很好的結果。

使用庫如jsoup將讓你一個不錯的對象模型,而不是穿越依靠字符串操作。

作爲獎勵,jsoup 實際上爲您設置HTML字符串的格式,如果您想要的話。

相關問題