java网页抓取
網頁抓取就是,我們想要從別人的網站上得到我們想要的,也算是竊取了,有的網站就對這個網頁抓取就做了限制,比如百度
直接進入正題
1 //要抓取的網頁地址 2 String urlStr = "http://**************/center"; 3 URL url = new URL(urlStr); 4 URLConnection connection = url.openConnection(); 5 //得到網頁的編碼方式 6 System.out.println(connection.getContentType()); 7 8 //讀取網頁的的內容 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();
?
很簡單,大家不用死記硬背,我的這個思想是,
1.通過一個url打開一個連接
2.通過這個連接來得到網頁的編碼方式
3.通過這個連接打開一個寫入流,我這里把這個網頁寫到我的本地了,大家在練習的時候隨意。
4.進行標準的寫入
5.最重要一步,關閉連接
就這么簡單的一個小網頁抓取。
防止你的網頁被別人抓取試用robots.txt,具體怎么還沒研究過,http://www.robotstxt.org/?這個是官網
測試你的網站是否生效了,直接http://網站名/robots.txt如果顯示,則證明成功。
轉載于:https://www.cnblogs.com/duwenlei/p/3480755.html
總結
- 上一篇: window.open和window.l
- 下一篇: 《梦仙》第十五句是什么