`
mushme
  • 浏览: 777590 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

下载知乎制定问题回答者的头像

 
阅读更多
如题,下载知乎制定问题回答者的头像
用jsoup实现解析
package info.frady;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 下载zhihu问题回答者的头像
 * @author frady
 *
 */
public class ZhihuDown {

	public static void main(String[] args) throws Exception {
		Map<String,String> imgMap=new HashMap<String,String>();
		String url="http://www.zhihu.com/question/36412655";//要抓取的问题
		Document documnet=Jsoup.connect(url).timeout(100 * 1000).get();
		
		Elements es1 = documnet.select("div.zu-main-content");
		for (Element e1 : es1) {
			Elements es2 = e1.select("h3.zm-item-answer-author-wrap");
			for (Element e2 : es2) {
				Elements es3 = e2.select("img.zm-list-avatar");//找到头像的部分了
				for (Element e3 : es3) {
					
					String imgUrl=e3.attr("src");
					imgUrl=imgUrl.substring(imgUrl.lastIndexOf("/")).substring(1);
					imgMap.put(imgUrl, imgUrl);//将头像地址存放到map中,可以防止默认头像被下载多次
				}
			}
		}
		
		for (Entry e : imgMap.entrySet()) {
			System.out.println("download..."+e.getKey().toString());
			download("http://pic1.zhimg.com/"+e.getKey().toString(), e.getKey().toString(),"d:\\image\\");
		}
		
	}
	
	public static void download(String urlString, String filename,String savePath) throws Exception {
	    // 构造URL
	    URL url = new URL(urlString);
	    // 打开连接
	    URLConnection con = url.openConnection();
	    //设置请求超时为5s
	    con.setConnectTimeout(5*1000);
	    // 输入流
	    InputStream is = con.getInputStream();
	
	    // 1K的数据缓冲
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
	    // 输出的文件流
	   File sf=new File(savePath);
	   if(!sf.exists()){
		   sf.mkdirs();
	   }
	   OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	    // 完毕,关闭所有链接
	    os.close();
	    is.close();
	} 

}


jsoup下载地址:http://jsoup.org/download
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics