用Java代碼來抓取網(wǎng)頁內(nèi)容有很多種方法,可以直接用網(wǎng)絡編程的知識鏈接到網(wǎng)站上用輸入輸出流的方式來讀取內(nèi)容,然后用正則表達是來解析流文件,得到自己想要的內(nèi)容。不過有人已經(jīng)將這種內(nèi)容封裝好了叫HTMLParser這個東西提供了很多的的方法可以使用,具體的網(wǎng)上有很多的例子 他有三種方式來解析這個網(wǎng)頁。下一節(jié)來說明他們之間的使用方式。
貼一個用URL的方式。這個代碼雖然能出結果,不過好像有問題,還望高人指點!!
package com.xjsx.gethtml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class GetHTML {
/**
* @param args
*/
public static void main(String[] args) {
try {
URL url = new URL("http://www.baidu.com");
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
// InputStream inputStream = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String date;
while ((date = reader.readLine()) != null) {
System.out.println(date);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}