• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

sou78

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

简单获取网页中特定图片

所列代码功能仅是爬取单个url网页内容中特定内容。

DefaultHttpClient httpClient = new DefaultHttpClient();
    private  HttpPost httppost;
    private  HttpResponse response;
public Crawler(int tag) {
     /*此处设置代理服务器,主要用来避免频繁抓取某一网站,而导致网站封杀爬虫,可以不用 HttpHost proxy
= new HttpHost("121.182.114.192", 9022); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
} public void run() { try { String crawlUrl = "http://www.baidu.com"; HttpPost httppost = new HttpPost(crawlUrl); response = httpClient.execute(httppost); String str = EntityUtils.toString(response.getEntity());
          /*正则匹配,获取自己所需要的内容 Pattern p
= Pattern.compile("data-resized=\"([^\"]*)\""); Matcher m = p.matcher(str);while (m.find()) { downPicture(m.group(1), dir,hotelId+""+i+".jpg"); } System.out.println(crawlUrl + "......SUCCESS"); httppost.abort(); } } catch (Exception e) { e.printStackTrace(); System.out.println("errorUrl ........................"); } mysql.close(); }
  /*下载图片
public boolean downPicture(String urlStr, String dir, String fileName) { try { URL url = new URL(urlStr); Image src = javax.imageio.ImageIO.read(url); int wideth = src.getWidth(null); int height = src.getHeight(null); BufferedImage tag = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(src, 0, 0, wideth, height, null); String path = "pic\\" + dir; File f = new File(path); if (!f.exists()) f.mkdirs(); FileOutputStream out = new FileOutputStream(path+"\\"+fileName); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }

 

posted on 2013-09-27 13:05  sou78  阅读(454)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3