java 简单的爬虫

这里介绍两种方式 

一.

1.maven构建一个

<dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.2</version>
        </dependency>

2.新建一个OneSpider

import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author lili
 */
public class OneSpider {

    public static void Get_Url(String url) {
        try {
        //用jsoup 获取网页
            Document doc = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                    .timeout(3000)
                    .get();
            //.data("query", "Java")
            //.userAgent("头部")
            //.cookie("auth", "token")
            //.timeout(3000)
            //.post()
            //得到html的所有东西(可以通过id 或者 class 获取html)
            Element content = doc.getElementById("content");
  //下面就是获取到的页面的解析数据
//            Elements content = doc.getElementsByClass("j-content");
            System.out.println("com.mycompany.spiderdemo.Test.Get_Url()" + content);
            //分离出html下<a>...</a>之间的所有东西
//            Elements links = content.getElementsByTag("a");
            //Elements links = doc.select("a[href]");
            // 扩展名为.png的图片
            Elements pngs = doc.select("img[src$=.png]");
            // class等于masthead的div标签
            Element masthead = doc.select("div.masthead").first();

//            for (Element link : links) {
//                //得到<a>...</a>里面的网址
//                String linkHref = link.attr("href");
//                //得到<a>...</a>里面的汉字
//                String linkText = link.text();
//                System.out.println(linkText);
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

3.新建一个主类

public class JavaSpider {
    //main函数

    public static void main(String[] args) {

        String url = "www.baidu.com";
        
        Test.Get_Url(url);
    }
}

4.打印出数据就可以看到了

.这种方式更高效 

2.1 Save_Html方法是将抓取的网页变成html文件,保存在本地

2.2 Get_Localhtml方法是 解析本地的html

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author lili
 */
public class TwoSpiderTest {
    //将抓取的网页变成html文件,保存在本地

    public static void Save_Html(String url) {
        try {
//存放html的文件夹需要先建好
            File dest = new File("src/temp_html/" + "1.html");
            //接收字节输入流
            InputStream is;
            //字节输出流
            FileOutputStream fos = new FileOutputStream(dest);

            URL temp = new URL(url);
            URLConnection uc = temp.openConnection();
            uc.addRequestProperty("User-Agent", "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5");
            is = temp.openStream();
            is = temp.openStream();
            //为字节输入流加缓冲             
            BufferedInputStream bis = new BufferedInputStream(is);
            //为字节输出流加缓冲
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            int length;

            byte[] bytes = new byte[1024 * 20];
            while ((length = bis.read(bytes, 0, bytes.length)) != -1) {
                fos.write(bytes, 0, length);
            }

            bos.close();
            fos.close();
            bis.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //解析本地的html
    public static void Get_Localhtml(String path) {
        //读取本地html的路径
        File file = new File(path);
        //生成一个数组用来存储这些路径下的文件名
        File[] array = file.listFiles();
        //写个循环读取这些文件的名字

        for (int i = 0; i < array.length; i++) {
            try {
                if (array[i].isFile()) {
                    //文件名字
                    System.out.println("正在解析网址:" + array[i].getName());

                    //下面开始解析本地的html
                    Document doc = Jsoup.parse(array[i], "UTF-8");
                    //得到html的所有东西
                    Element content = doc.getElementById("content");
                    //分离出html下<a>...</a>之间的所有东西
                    Elements links = content.getElementsByTag("a");
                    //Elements links = doc.select("a[href]");
                    // 扩展名为.png的图片
                    Elements pngs = doc.select("img[src$=.png]");
                    // class等于masthead的div标签
                    Element masthead = doc.select("div.masthead").first();

                    for (Element link : links) {
                        //得到<a>...</a>里面的网址
                        String linkHref = link.attr("href");
                        //得到<a>...</a>里面的汉字
                        String linkText = link.text();
                        System.out.println(linkText);
                    }
                }
            } catch (Exception e) {
                System.out.println("网址:" + array[i].getName() + "解析出错");
                e.printStackTrace();
                continue;
            }
        }
    }
}

2.3 在主类里面 放入url地址 就可以了

public class JavaSpider {
    //main函数

    public static void main(String[] args) {
        String url = "www.baidu.com";
        String path = "src/temp_html/";
//将html存放在本地
         TwoSpiderTest.Save_Html(url);
//解析本地的html
         TwoSpiderTest.Get_Localhtml(path);

    }
}

猜你喜欢

转载自my.oschina.net/u/2428630/blog/1608704