****************根據網址獲取指定的網頁內容********************
private static String getHtml(String path){
StringBuffer html = new StringBuffer();//保存整個html文檔的數據
try {
//1.發起一個url網址的請求
URL url = new URL(path);
URLConnection connection = url.openConnection();
//2.獲取網頁的數據流
InputStream input = connection.getInputStream(); //字節流 一個字節一個字節的讀取 中文佔用兩個字節
InputStreamReader reader = new InputStreamReader(input,"GBK"); //字符流 一個字符一個字符的讀取 可指定字符集編碼 ,常用字符集編碼:GBK,GB2312,utf-8,ISO-8859-1
BufferedReader bufferedReader = new BufferedReader(reader); //字符流 一行一行的讀取
//3.解析並且獲取InputStream中具體的數據,並且輸出到控制檯
String line = "";
while((line = bufferedReader.readLine()) != null)
{
html.append(line); //將所有讀到的每行信息line追加到(拼接到)html對象上
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return html.toString();
}
****************解析html網頁內容********************
private static List parseHtml(String html) {
// 2.解析html網頁內容
Document document = Jsoup.parse(html);
// 獲取所有的招聘信息所在的div節點
Element div = document.getElementById("resultList");
// 獲取div中所有的招聘信息的div
Elements jobs = div.getElementsByClass("el");
List<Job> jobList = new ArrayList<Job>();
for (Element job : jobs) {
// 工作名稱
String jobName = job.getElementsByClass("t1").get(0).text().toUpperCase();
jobName = parseJob(jobName);
// 公司名稱
String company = job.getElementsByClass("t2").get(0).text();
// 工作地點
String address = job.getElementsByClass("t3").get(0).text();
// 薪酬待遇
String salary = job.getElementsByClass("t4").get(0).text();
// 求平均值
double avgSalary = getAvgSalary(salary);
// 封裝招聘信息
Job myJob = new Job();
myJob.setJobName(jobName);
myJob.setCompany(company);
myJob.setAddress(address);
myJob.setSalary(avgSalary);
// 將對象添加到集合裏面
jobList.add(myJob);
}
return jobList;
}
*******************解釋***********************
通過訪問某網站地址之後,設置讀的方式,解析內容,可以先去網頁確認你要爬取的數據,進入開發者模式(F12),看網頁的結構是怎樣的,程序中是先拿到節點id爲resultList,裏面的一行一行數據的class都爲el,分析網頁即可以找到有用的信息,這樣就可以更準確地爬到想要的數據
拿到數據之後,將一條條信息進行封裝,然後把封裝的信息添加到集合中,如果要對數據進行一些處理,可以將處理信息的方法封裝一下調用即可。
接下來,開始數據庫操作……
*********************END*************************