java网页抓取
網(wǎng)頁(yè)抓取就是,我們想要從別人的網(wǎng)站上得到我們想要的,也算是竊取了,有的網(wǎng)站就對(duì)這個(gè)網(wǎng)頁(yè)抓取就做了限制,比如百度
直接進(jìn)入正題
1 //要抓取的網(wǎng)頁(yè)地址 2 String urlStr = "http://**************/center"; 3 URL url = new URL(urlStr); 4 URLConnection connection = url.openConnection(); 5 //得到網(wǎng)頁(yè)的編碼方式 6 System.out.println(connection.getContentType()); 7 8 //讀取網(wǎng)頁(yè)的的內(nèi)容 9 BufferedReader read = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); 10 File file = new File("d:/test.html"); 11 BufferedWriter write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); 12 if(read != null){ 13 String s = null; 14 while((s = read.readLine()) != null){ 15 System.out.println(s); 16 write.write(s); 17 write.flush(); 18 } 19 read.close(); 20 write.close();
?
很簡(jiǎn)單,大家不用死記硬背,我的這個(gè)思想是,
1.通過(guò)一個(gè)url打開(kāi)一個(gè)連接
2.通過(guò)這個(gè)連接來(lái)得到網(wǎng)頁(yè)的編碼方式
3.通過(guò)這個(gè)連接打開(kāi)一個(gè)寫(xiě)入流,我這里把這個(gè)網(wǎng)頁(yè)寫(xiě)到我的本地了,大家在練習(xí)的時(shí)候隨意。
4.進(jìn)行標(biāo)準(zhǔn)的寫(xiě)入
5.最重要一步,關(guān)閉連接
就這么簡(jiǎn)單的一個(gè)小網(wǎng)頁(yè)抓取。
防止你的網(wǎng)頁(yè)被別人抓取試用robots.txt,具體怎么還沒(méi)研究過(guò),http://www.robotstxt.org/?這個(gè)是官網(wǎng)
測(cè)試你的網(wǎng)站是否生效了,直接http://網(wǎng)站名/robots.txt如果顯示,則證明成功。
轉(zhuǎn)載于:https://www.cnblogs.com/duwenlei/p/3480755.html
總結(jié)
- 上一篇: window.open和window.l
- 下一篇: 《梦仙》第十五句是什么