Java 简单爬虫 代码

这里只演示最简单的一个爬虫

准备:需要导入一个jar包>> jsoup 下载链接

(jsoup 是用于爬虫的一个框架,除此之外的还有jSpider、HTMLUnit 、Jaunt)

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

class SimpleSpider{
	Document getDoc(String url) throws IOException {
		Document doc=Jsoup.connect(url).get();
		return doc;
	}
	Elements getElementAs(Document doc) {//cssQuery syntax:https://jsoup.org/apidocs/org/jsoup/select/Selector.html
		Elements a=doc.select("a[href]");//finds links (a tags with href attributes)						
		return a;
	}
}
public class SimpleOne {
	public static void main(String[] args) throws IOException {
		SimpleSpider s=new SimpleSpider();
		Document doc=s.getDoc("https://www.baidu.com/");
		//System.out.println(s.getElementAs(doc));
		Elements aSet=s.getElementAs(doc);
		for(Element i :aSet) {
			System.out.println(i.attr("href"));//get attr href
		}
		System.out.println("end");
	}

}

我现在也只是刚接触,发现利用这些框架的话,其实Java 爬虫看起来也没那么冗余

网页解析起来也不复杂

不过,你如果不借助这些框架的话。。

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class WithNoExtraJar {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		URL url;
	    InputStream is = null;
	    DataInputStream dis;
	    String line;
	    try {
	        url = new URL("https://www.baidu.com/");
	        is = url.openStream();  // get connection
	        dis = new DataInputStream(new BufferedInputStream(is));

	        while ((line = dis.readLine()) != null) {
	            System.out.println(line);
	        }
	    } catch (MalformedURLException mue) {
	         mue.printStackTrace();
	    } catch (IOException ioe) {
	         ioe.printStackTrace();
	    } finally {
	        try {
	            is.close();
	        } catch (IOException ioe) {
	            // nothing to see here
	        }
	    }
	}

}

上面只是获取网页源代码的程序,都还没开始解析,就已经一大坨了,看了就头大

所以,还是用框架好。。


除了Java,还有挺多语言也可以写爬虫的

比如说:

Ruby、node.js、python、C++、php

各有特点吧,不过现在最火的是python

Java 的话,我个人认为,多线程不赖了

(Google和百度都查了,真的找不到有人对Java爬虫的评价,噗 好像是故意被冷落了)

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值