Java爬虫Jsoup -- 解析URL、String、File

package xxx.xxx.xxx;

import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Test;

import java.io.File;
import java.net.URL;

public class JsoupFirstTest {
    @Test
    public void testUrl()throws Exception{
//        解析url地址,第一个参数是访问的url,第二个参数是访问时候的超时时间
        Document doc  = Jsoup.parse (new URL("http://itcast.cn"),  1000);
//    使用标签选择器,获取title标签中的内容
        String title = doc.getElementsByTag( "title").first().text();
//        打印
        System.out.println(title);
    }

    @Test
    public  void testString() throws Exception{
        String content = FileUtils.readFileToString(new File("C:\\Users\\tree\\Desktop\\test.html"),"utf8");
        Document doc = Jsoup.parse(content);
        String title = doc.getElementsByTag("title").first().text();
        System.out.println(title);
    }

    @Test
    public void testFile() throws Exception{
        Document doc = Jsoup.parse(new File("C:\\User\\tree\\Desktop\\test.html"), "utf8");
        String title = doc.getElementsByTag("title").first().text();
        System.out.println(title);
    }
}

}

结果:

在这里插入图片描述

虽然使用Jsoup可以替代HTTPClient直接发起请求解析数据,但是往往不会这样用,因为实际的开发过程中,需要使用到多线程、连接池,代理等等方法,而jsoup对这些的支持并不是很好。所以我们一般把jsoup仅仅作为Html解析工具使用。

发布了81 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43542074/article/details/103113294
今日推荐