使用HttpClient实现一个简单爬虫,抓取煎蛋妹子图
這只蟲子的功能很簡單,抓取到”煎蛋網(wǎng)xxoo”網(wǎng)頁(http://jandan.net/ooxx/page-1537),解析出其中的妹子圖,保存至本地。
先放結(jié)果:
從程序來講,分為三個步驟:
1、發(fā)起一個http請求,獲取返回的response內(nèi)容;
2、解析內(nèi)容,分離出有效圖片的url;
3、根據(jù)這些圖片的url,生成圖片保存至本地。
開始詳細(xì)說明:
準(zhǔn)備工作:HttpClient的Jar包,訪問http://hc.apache.org/?? 自行下載。
主程序內(nèi)容:
public class SimpleSpider {//起始頁碼private static final int page = 1538;public static void main(String[] args) {//HttpClient 超時(shí)配置RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();System.out.println("5秒后開始抓取煎蛋妹子圖……");for (int i = page; i > 0; i--) {//創(chuàng)建一個GET請求HttpGet httpGet = new HttpGet("http://jandan.net/ooxx/page-" + i);httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36");httpGet.addHeader("Cookie","_gat=1; nsfw-click-load=off; gif-click-load=on; _ga=GA1.2.1861846600.1423061484");try {//不敢爬太快Thread.sleep(5000);//發(fā)送請求,并執(zhí)行CloseableHttpResponse response = httpClient.execute(httpGet);InputStream in = response.getEntity().getContent();String html = Utils.convertStreamToString(in);//網(wǎng)頁內(nèi)容解析new Thread(new JianDanHtmlParser(html, i)).start();} catch (Exception e) {e.printStackTrace();}}} }HttpClient是一個非常強(qiáng)大的工具,屬于apache下項(xiàng)目。如果只是創(chuàng)建一個默認(rèn)的httpClient實(shí)例,代碼很簡單,官網(wǎng)手冊上有詳細(xì)說明。
可以看到在創(chuàng)建一個GET請求時(shí),加入了請求頭。第一個User-Agent代表所使用瀏覽器。有些網(wǎng)站需要明確了解用戶所使用的瀏覽器,而有些不需要。個人猜測,部分網(wǎng)站根據(jù)用戶使用瀏覽器不同顯示不一樣。這里的煎蛋網(wǎng),就必須得加入請求頭。第二個Cookie則代表了一些用戶設(shè)置,可以沒有。使用chrome的開發(fā)者工具就能清楚看到。如果是https加密后的,則需要特殊的抓包工具。
?
網(wǎng)頁內(nèi)容解析
public class JianDanHtmlParser implements Runnable {private String html;private int page;public JianDanHtmlParser(String html,int page) {this.html = html;this.page = page;}@Overridepublic void run() {System.out.println("==========第"+page+"頁============");List<String> list = new ArrayList<String>();html = html.substring(html.indexOf("commentlist"));String[] images = html.split("li>");for (String image : images) {String[] ss = image.split("br");for (String s : ss) {if (s.indexOf("<img src=") > 0) {try{int i = s.indexOf("<img src=\"") + "<img src=\"".length();list.add(s.substring(i, s.indexOf("\"", i + 1)));}catch (Exception e) {System.out.println(s);}}}}for(String imageUrl : list){if(imageUrl.indexOf("sina")>0){new Thread(new JianDanImageCreator(imageUrl,page)).start();}}} }這段代碼看起來凌亂,但實(shí)際上卻特別簡單。簡單說便是,將response返回的html字符串解析,截取,找到真正需要的內(nèi)容(圖片url),存入到臨時(shí)容器中。
生成圖片類
public class JianDanImageCreator implements Runnable {private static int count = 0;private String imageUrl;private int page;//存儲路徑,自定義private static final String basePath = "E:/jiandan"; public JianDanImageCreator(String imageUrl,int page) {this.imageUrl = imageUrl;this.page = page;}@Overridepublic void run() {File dir = new File(basePath);if(!dir.exists()){dir.mkdirs();System.out.println("圖片存放于"+basePath+"目錄下");}String imageName = imageUrl.substring(imageUrl.lastIndexOf("/")+1);try {File file = new File( basePath+"/"+page+"--"+imageName);OutputStream os = new FileOutputStream(file);//創(chuàng)建一個url對象URL url = new URL(imageUrl);InputStream is = url.openStream();byte[] buff = new byte[1024];while(true) {int readed = is.read(buff);if(readed == -1) {break;}byte[] temp = new byte[readed];System.arraycopy(buff, 0, temp, 0, readed);//寫入文件 os.write(temp);}System.out.println("第"+(count++)+"張妹子:"+file.getAbsolutePath());is.close(); os.close();} catch (Exception e) {e.printStackTrace();}} }根據(jù)每個圖片的src地址創(chuàng)建一個URL對象,再使用字節(jié)流,生成本地文件。
這個程序相對來說比較簡單,純屬娛樂。如果能讓那些不了解HttpClient的同學(xué)對這個庫產(chǎn)生興趣,則功德無量。
github地址:https://github.com/nbsa/SimpleSpider
PS:這個博客只提供抓取圖片的方法,圖片版權(quán)屬于原網(wǎng)站及其網(wǎng)友。請大家尊重原網(wǎng)勞動成果,避免分發(fā)、傳播圖片內(nèi)容。
from:?http://www.cnblogs.com/nbspL/p/4780792.html?utm_source=tuicool&utm_medium=referral
總結(jié)
以上是生活随笔為你收集整理的使用HttpClient实现一个简单爬虫,抓取煎蛋妹子图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机视觉研究群体及专家主页汇总
- 下一篇: 从0开始学习 GitHub 系列之「初识