Jsoup专题

maven中引入Jsoup

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

不同形式获取Document

//获取远程url
String url = "https://angular.cn/docs/ts/latest/guide/animations.html";
Document doc = Jsoup.connect(url).get();
//获取本地文件
File file = new File("G:/test.xml");
Document doc = Jsoup.parse(file, "UTF-8");
//直接解析字符串
String html="<html></html>";
Document doc = Jsoup.parse(html);

标签查找

//1. 查找指定标签名的标签
        String path = "G:/test.xml";
        File file = new File(path);
        Document doc;
        doc = Jsoup.parse(file, "UTF-8");
        Elements es = doc.select("pro");
        for (int i = 0; i < es.size(); i++) {
            System.out.println(es.get(i));
        }
//2.查看标签中的文本内容
System.out.println(es.get(i).html());

属性查找

//1. 查找包含某属性名的标签
Elements es = doc.getElementsByAttribute("name");
或
Elements es = doc.select("[name]");
//2. 查找以某属性名开头的标签
Elements es = doc.getElementsByAttributeStarting("nam");
//3. 查找属性与值匹配的标签
Elements es = doc.getElementsByAttributeValue("name", "mypro");
或
Elements es = doc.select("[name=mypro]");
//4. 查找name属性的属性值包含mypro的标签
Elements es = doc.getElementsByAttributeValueContaining("name", "mypro");
或
Elements es = doc.select("[name~=mypro]");
//5. 查找含某类属性标签
Elements es = doc.getElementsByClass("mycss");

联合查询

//1. 查找pro标签带class属性的标签
Elements es = doc.select("pro").select("[class]");

内容插入

//1. 在标签后插入
Elements es = doc.select("pro");
        es.last().after("哈哈");
//2. 在标签中插入
es.last().append("哈哈");
//3. 在标签前插入
es.last().before("哈哈");
//4. 标签中插入文档中的标签
es.last().after(doc.select("pro").select("[name=mypro]").outerHtml());
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,477评论 19 139
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 11,158评论 0 4
  • 曾经学过一篇文章---寒号鸟,讲的是一只生活在北方的小鸟,临近冬天了,其他鸟类开始筑巢收集柔暖的草叶准备过冬了...
    niu魔王阅读 4,191评论 0 1
  • 《战狼2》又火了,票房就像毒药,一下子让人沉浸其中不能自拔。吴京的硬汉形象更是刮起了一阵旋风。此片我没看过,似乎没...
    欢颜589阅读 4,048评论 0 2
  • 文/尚德老徐 良大师说:他有一个目标,就是在深圳开一间茶馆,不为挣钱,就为听故事。然后把这些故事写成小说。 据说郭...
    尚德茶香阅读 5,556评论 16 16