为了账号安全,请及时绑定邮箱和手机立即绑定

Java爬虫(一)入门篇---Jsoup工具

标签:
Python 爬虫

前言

之前工作中需要用到爬虫,就去学习了几种Java爬虫工具,也了解pythoy的scrapy框架也是大名鼎鼎,但是据了解可能不太适合我们的业务,所以以下所要介绍的均为Java框架下的爬虫

一、准备工作

1、下载jsoup工具,如果是maven项目,请在pm.xml中加入以下代码:

jsoup虽然不是一个很强大的爬虫工具,但是它对于网页html文档的各种处理确实是很强大的,同时自身也是个非常好用的爬虫,也许无法去做较大难度的数据的抓取,但我认为它是个非常优良的文档处理助手

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

2、确定所要抓取的网站地址:

这里我以百度数据为例:
搜索 “互联网” 相关数据,

图片描述
获取如上网页中所显示的信息,
下面就开始编写jsoup爬虫代码;

/**
	 * 准备抓取的目标地址,%E4%BA%92%E8%81%94%E7%BD%91 为utf-8格式的 互联网
	 */
	private static String url = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=互联网";
	
	public static void main(String[] args) throws Exception {
		//链接到目标地址
		Connection connect = Jsoup.connect(url);
		//设置useragent,设置超时时间,并以get请求方式请求服务器
		Document document = connect.userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)").timeout(6000).ignoreContentType(true).get();
		Thread.sleep(1000);
		//获取指定标签的数据
		Element elementById = document.getElementById("content_left");
		//输出文本数据
		System.out.println(elementById.text());
		//输出html数据
		System.out.println(elementById.html());
	}

查询结果如下:

图片描述

以上方式就是使用jsoup获取文本数据的基本操作,下面我们继续尝试在以上基础上获取页面中所有的图片

/**
	 * 准备抓取的目标地址,%E4%BA%92%E8%81%94%E7%BD%91 为utf-8格式的 互联网
	 */
	private static String url = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=互联网";
	
	public static void main(String[] args) throws Exception {
		//链接到目标地址
		Connection connect = Jsoup.connect(url);
		//设置useragent,设置超时时间,并以get请求方式请求服务器
		Document document = connect.userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)").timeout(6000).ignoreContentType(true).get();
		Thread.sleep(1000);
		//获取指定标签的数据
		Element elementById = document.getElementById("content_left");
		//输出文本数据
		//System.out.println(elementById.text());
		//输出html数据
		//System.out.println(elementById.html());
		
		//获取所有图片链接
		Elements imgtag = document.getElementsByTag("img");
		List<String> imgurlList = new ArrayList<String>();
		for (int i = 0; i < imgtag.size(); i++) {
			if (StringUtils.isNotEmpty(imgtag.get(i).attr("src"))&&imgtag.get(i).attr("src").startsWith("http")) {
				System.out.println(imgtag.get(i).attr("src"));
			}
		}
	}

输出如下:
图片描述

由上可以获取到图片链接,下面就是使用jsoup把图片下载下来了,有兴趣的朋友可以试试用这种方法去抓取淘宝商品图片,会更简单方便

根据图片链接下载图片

    /**
     * 下载图片到指定目录
     *
     * @param filePath 文件路径
     * @param imgUrl   图片URL
     */
    public static void downImages(String filePath, String imgUrl) {
        // 若指定文件夹没有,则先创建
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 截取图片文件名
        String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length());

        try {
            // 文件名里面可能有中文或者空格,所以这里要进行处理。但空格又会被URLEncoder转义为加号
            String urlTail = URLEncoder.encode(fileName, "UTF-8");
            // 因此要将加号转化为UTF-8格式的%20
            imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1) + urlTail.replaceAll("\\+", "\\%20");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 写出的路径
        File file = new File(filePath + File.separator + fileName);

        try {
            // 获取图片URL
            URL url = new URL(imgUrl);
            // 获得连接
            URLConnection connection = url.openConnection();
            // 设置10秒的相应时间
            connection.setConnectTimeout(10 * 1000);
            // 获得输入流
            InputStream in = connection.getInputStream();
            // 获得输出流
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            // 构建缓冲区
            byte[] buf = new byte[1024];
            int size;
            // 写入到文件
            while (-1 != (size = in.read(buf))) {
                out.write(buf, 0, size);
            }
            out.close();
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

有问题欢迎交流与指正,谢谢

点击查看更多内容
3人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消