其實是在2個小時前我是不會的,剛好有人在羣裏問了,趁着手裏項目結束的小日子,學習一下
需求如下,把該網頁上的數據爬取下來
1.爬取頁面
爬取頁面,就用的 最基礎的 HttpURLConnection,
/**
* 向指定URL發送GET方法的請求
*
* @param httpurl 請求參數用?拼接在url後邊,請求參數應該是 name1=value1&name2=value2 的形式。
* @return result 所代表遠程資源的響應結果
*/
public static String doGet(String httpurl ) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回結果字符串
try {
// 創建遠程url連接對象
URL url = new URL(httpurl);
// 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類
connection = (HttpURLConnection) url.openConnection();
// 設置連接方式:get
connection.setRequestMethod("GET");
// 設置連接主機服務器的超時時間:15000毫秒
connection.setConnectTimeout(15000);
// 設置讀取遠程返回的數據時間:60000毫秒
connection.setReadTimeout(60000);
// 發送請求
connection.connect();
// 通過connection連接,獲取輸入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封裝輸入流is,並指定字符集
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// 存放數據
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉資源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();// 關閉遠程連接
}
return result;
}
2 使用 jsoup 解析數據
package test;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
public class test {
public static void main(String[] args) {
List<HtmlEntity> htmlEntityList = new ArrayList<HtmlEntity>();
Document doc = Jsoup.parse(HttpUtil.doGet("http://www.lit.edu.cn/xwzx/xwkx.htm"));
//過濾對應標籤
Elements elements = doc.select("span[class=Article_Title]");
// 因爲jsp頁面使用了baseurl 所以要自己去手動替換
for (Element element : elements) {
htmlEntityList.add(new HtmlEntity(element.text(),
element.select("a").attr("href").replace(".."," http://www.lit.edu.cn")));
}
System.out.println(htmlEntityList);
}
}
使用實體類
public class HtmlEntity {
public String title;
public String url;
public HtmlEntity(String title, String url) {
this.title = title;
this.url = url;
}
@Override
public String toString() {
return "HtmlEntity{" +
"title='" + title + '\'' +
", url='" + url + '\'' +
'}'+'\n';
}
}