zoukankan      html  css  js  c++  java
  • java爬虫入门,一个简单的jsoup教程(1)

    jsoup是一款简单好用的页面解析工具,百度可以找到中文教程,我这里只是作为个人笔记的总结。

    首先是下载jar包,有三个在页面:https://jsoup.org/download 处可以找到下载.下载好了放进项目里就好

    然后构建一个普通的javaSE项目。。。

    获取页面之前首先第一步应该是了解DOM结构,这里不深入说明。

    然后就是这个工具的继承关系:Document继承Element继承NodeTextNode继承 Node

    然后我们开始做第一步操作document对象

        public void test1(){
                //暂时用字符串代替从页面取来的dom结构
                String html= "<html><head><title>First parse</title></head><body><p id='hehe'>Parsed HTML into a doc.</p></body></html>";
                //解析字符串获得document对象
                Document doc=Jsoup.parse(html);
                //从doc对象中取得id为hehe的元素然后获取其中的文字值
               System.out.println(doc.getElementById("hehe").text());
               //从doc对象中取得id为hehe的元素然后获取其中的html对象
               System.out.println(doc.getElementById("hehe").html());
               //从doc对象中取得id为hehe的元素然后回溯出整体
               System.out.println(doc.getElementById("hehe").root());
                //你可以把document对象看做后台版的js,通过class找,name找甚至利用jQuery都是支持的
        }
    通过第一步主要熟悉了操作这个对象,然后的话我们进入第二步,从网页中获取信息。

    很遗憾的是我当时在操作官方的学习文档时发现他丫居然放了个反爬虫链接,导致链接超时,所以我就写了这篇日志。第一步找到一个可爬的站点。然后开始爬。

    public void test2(){
            try {
                Document doc=Jsoup.connect("http://www.jb51.net")
                                  .data("query", "java")
                      .userAgent("Chrome")
                      .cookie("auth", "token")
                      .timeout(3000)
                      .post(); System.out.println(doc.getElementById(
    "trigger").text()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

    目前这个站点是可以爬的,不然你们可以试试其他的~~~~这里面有请求,浏览器,cookie,请求时间,请求方式等设置,你高兴的话.get()也是足够访问的。但是不设置时间容易受网络影响报错

    然后我们开始爬本机的html

        //解析本地文件为dom文档
        public void test3(){
            //文件路径转化为输入流对象
            File input = new File("/tmp/input.html");
            try {
                //解析输入流为dom对象。第三个为路径的头
                Document doc = Jsoup.parse(input, "UTF-8","");
                System.out.println(doc);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }

    到这里一个简单的爬虫就弄好了。

  • 相关阅读:
    fastcgi与cgi的区别
    oracle启动脚本
    oracle表空间大小的限制和DB_BLOCK_SIZE的概念
    静默安装Oracle11G
    ls 指令的介绍
    cronolog日志切割catalina.out
    oracle expdp自动备份脚本
    tomcat开启自启动
    oracle listener.ora文件配置
    CentOS 7.0 上安装和配置 VNC 服务器
  • 原文地址:https://www.cnblogs.com/blackdeng/p/6802126.html
Copyright © 2011-2022 走看看