使用java做最简单的爬虫,爬取图片

本文介绍了一个简单的网页图片爬虫实现过程,包括使用Java和jQuery从指定网页抓取并解析图片资源,最后下载到本地的方法。

第一步:index.jsp页面输入要爬取的网址

    <form action="result.jsp" method="post">
        <input type="text" name="url"><br>
        <input type="submit" value="抓取">
    </form>

第二步:目标result.jsp页面使用java(Downimg.java)和jquery爬取网址源码,并解析出所有img

java用来创建输入输出流

package com.pc.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Downimg {

    //首先我们要抓取图片
    //1.找到图片存放的位置
    //2.获取网页源代码
    /*
     * @Description:获取网页源代码
     * @Title:获取网页源代码
     * @Param_link:网页网址
     * @Param_encoding:编码
     * 
     * */
     
    
    //下载函数
    public static boolean download(String netImg,String Path){
        
        try {
            //建立图片的网络链接
        URL url=new URL(netImg);
        //打开链接

        URLConnection urlConnection=url.openConnection();
        //创建一个输入流存储,将目标流打入文件
        InputStream inputStream=urlConnection.getInputStream();
        File file=new  File(Path);
        
        //创建一个输出流,将文件流输出
        FileOutputStream outputStream=new FileOutputStream(file);
        
        int i=0;
        while((i=inputStream.read())!=-1) {
            outputStream.write(i);
        }
        
        //关闭流,先开后关
        outputStream.close();
        inputStream.close();
        return true;
        
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
    
    
    public static String htmlSource(String link,String encoding) {
        //因为作用域问题,所以提取出来
        InputStreamReader in=null;
        //因后面需要长久的存储,故创建一个sb
        StringBuffer sBuffer=new StringBuffer();
       //建立网络连接
        try {
       //异常捕获,提前处理,使用try catch
            URL url=new URL(link);
       //打开链接
            URLConnection uConnection=url.openConnection();
        //模拟浏览器登录
            uConnection.setRequestProperty("User-Agent", "java");
        //文件的传输  IO流
            InputStream inputStream=uConnection.getInputStream();
             in=new InputStreamReader(inputStream,encoding);
        //下载源代码
            //创建一个临时文件
            String line=null;
            //通过while循环进行逐行读取
            //因为  in只能一次读一个,所以用bufferreader 
            
            BufferedReader reader=new BufferedReader(in);
            while((line=reader.readLine())!=null) {
                //System.out.println(line);
                //因为line是临时数据不可能长久保存,故顶一个SBuffer
                sBuffer.append(line+"\n");
            }        
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//因为创建了流,所以需要创建finall去关闭
        finally {
              try {
                if(null!=in) {
                    in.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        
        
        return sBuffer.toString();
    }
    
    public static void main(String[] args) {
        System.out.println("Java里最牛逼的方法");
        download("http://pics.sc.chinaz.com/files/pic/pic9/201804/zzpic11491.jpg", "D:/VS/1.jpg");
    }
}
 

   jsp中使用jquery解析img

<%@page import="com.pc.util.Downimg"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<%
   //获取url
   String url=request.getParameter("url");
   String htmlSource=Downimg.htmlSource(url, "gbk");
   pageContext.setAttribute("htmlSource", htmlSource);
   System.out.print(url);
%>
<body>
  <div>
    <h1>你获取的数据</h1><br>
    <textarea id="source" style="height:400px;width:1000px;overflow=auto;">${htmlSource}</textarea>
         </div><br>
    <form action="download.jsp" method="post" id="formf">
         <label>符合条件的图片有:</label>
        
    <input type="submit" value="下载图片">
    </form>
    <br>


   <script type="text/javascript">
      $(function() {
          //获取里面的值
            var source = $("#source").val();
            var $source=$(source);
            //分析源码获取图片
            $source.find("img").each(function(){
                var src=$(this).attr("src");
                if(src!=""&&src.length>0){
                    if (src.indexOf(".jpg")!=-1||src.indexOf(".png")!=-1||src.indexOf(".prf")!=-1) {
                        $("body").append("<div style='float:left;margin:10px;'><img src='"+src+"' width='180' height='180'></div>");
                        $("#formf").append("<input type='text' name='test' style='height:1px;width:1px;display:none;' value='"+src+"'/>");
                    }
                }
            })
        });
      
   </script>
</body>
</html>

第三步:创建下载调用页面,调用之前java代码中的下载逻辑把缓存的img通过流方式下载,download.jsp

<%@page import="com.pc.util.Downimg"%>
<%@page import="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<body>
<% 


     String[] imgs=request.getParameterValues("test");   
     String imgpath="d:/Test/downPC";
     System.out.println(imgpath);
     System.out.println(imgs[0].toString());
     

     File file=new File(imgpath);
     //如果没有这个文件夹,就创建一个
     if(!file.exists()){
         file.mkdirs();
     }
      //遍历下载
     for(String img:imgs){
         System.out.println(img);
         String filename=img.substring(img.lastIndexOf("/")+1,img.length());
        System.out.println(filename);
         Downimg.download(img,imgpath+"/"+filename);
         out.print("<img src='down/'"+filename+">");
     }
    %>

</body>
</html>

 

//声明:此方法由多个视频教学总结归纳

### 回答1: 好的,我会尽力回答你的问题。 要写一个爬取图片爬虫,你可以使用 Java 的网络编程库来发送 HTTP 请求并解析 HTML 页面。在这里,我们假设你已经了解了 Java 基础知识,包括如何编写程序、创建类和对象、使用循环和条件语句等。 首先,你需要导入 Java 的网络编程库,例如 java.net.URL 和 java.net.HttpURLConnection。然后,你可以使用这些类来打开一个连接到指定网站的流,并使用流来读取网站的 HTML 内容。 接下来,你可以使用正则表达式或者其他方法来解析 HTML 页面,并提取你想要的图片链接。最后,你可以使用 Java 的 I/O 类(例如 java.io.BufferedInputStream 和 java.io.FileOutputStream)来下载图片并将它们保存到本地。 下面是一个简单的例子,展示了如何使用 Java 的网络编程库来发送 HTTP 请求并读取返回的 HTML 内容: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Main { public static void main(String[] args) { try { // 创建一个 URL 对象 URL url = new URL("http://www.example.com"); // 打开一个 HTTP 连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请 ### 回答2: 要编写一个使用Java编写的爬虫爬取图片,可以按照以下步骤进行操作: 1. 首先,引入相关的Java类库,如Jsoup等,以便处理HTML页面和网络请求。 2. 使用Jsoup库发送HTTP GET请求,获取目标网页的HTML源代码。 3. 解析HTML源代码,通过Jsoup提供的DOM操作方法,从中提取出所有图片的URL链接。 4. 通过网络请求,逐一下载这些图片。可以使用Java的URL和URLConnection类来发送HTTP请求,将图片保存到本地文件系统中。 5. 针对爬取图片,可以设定一些过滤条件,如文件的大小、尺寸、类型等,以确保只下载符合要求的图片。 以下是一个示例代码片段,用于演示上述步骤: ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class ImageCrawler { public static void main(String[] args) { String targetUrl = "http://example.com"; // 目标网页的URL地址 try { // 发送HTTP GET请求,获取HTML源代码 Document document = Jsoup.connect(targetUrl).get(); // 从HTML源代码中提取所有图片的URL链接 Elements imgTags = document.select("img"); for (Element imgTag : imgTags) { String imgUrl = imgTag.absUrl("src"); if (imgUrl.startsWith("http")) { // 下载图片 saveImage(imgUrl); } } } catch (IOException e) { e.printStackTrace(); } } public static void saveImage(String imageUrl) throws IOException { URL url = new URL(imageUrl); URLConnection conn = url.openConnection(); try (InputStream in = conn.getInputStream(); FileOutputStream out = new FileOutputStream("path/to/save/image.jpg")) { byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } } } } ``` 以上示例代码仅实现了简单的图片爬取功能,仍有一些细节需要根据实际需求进行补充。例如,在下载图片时,可以使用多线程或使用线程池来提高效率。此外,还应添加异常处理、日志记录、合适的HTTP请求头等功能,以防止被目标网站封禁或触发反爬虫机制。 ### 回答3: 要用Java写一个爬取图片爬虫,可以使用Jsoup库来实现。以下是大致的步骤和代码示例: 步骤一:导入Jsoup库 首先,需要确保已经将Jsoup库添加到Java项目中。可以在Maven或Gradle的项目配置文件中添加相应的依赖项,或者手动下载并添加Jsoup.jar文件。 步骤二:编写爬虫代码 1. 创建一个Java类,比如名为ImageCrawler的类。 ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; public class ImageCrawler { public static void main(String[] args) { String url = "https://www.example.com"; // 设置目标网站的URL try { Document doc = Jsoup.connect(url).get(); // 获取网页内容 Elements images = doc.select("img[src]"); // 获取所有图片元素 for (Element img : images) { String imageURL = img.absUrl("src"); // 获取图片的绝对URL // 下载图片到本地 String fileName = imageURL.substring(imageURL.lastIndexOf('/') + 1); URL imageURLObj = new URL(imageURL); BufferedInputStream in = new BufferedInputStream(imageURLObj.openStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer, 0, 1024)) != -1) { out.write(buffer, 0, bytesRead); } out.close(); in.close(); } } catch (IOException e) { e.printStackTrace(); } } } ``` 2. 在上述代码中,首先指定目标网站的URL。然后,使用Jsoup的connect方法获取网页内容,并选择所有img标签。通过遍历图片元素,可以获取图片的绝对URL,然后使用java.net包中的相关类下载图片到本地。 步骤三:运行爬虫 保存并编译上述Java类后,可以运行它来启动爬虫爬虫将会将目标网站上的所有图片下载到当前工作目录。 请注意,根据目标网站的不同,还可能需要一些额外的处理,比如处理相对URL,或者设置请求头部信息,以避免被反爬虫机制拦截。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值