【获取HTML字符串中标签的属性值】

java中Document获取HTML字符串中的某一个标签的指定属性

		String html = "<html><head><title>高克莱的一段html</title></head>"
                + "<body><h1>这是一段html</h1>"
                + "<p>点击网站名称访问网页</p>"
                + "<a href=\"https://www.baidu.com\">百度</a>"
                + "<a href=\"https://www.taobao.com\">淘宝</a>"
                + "<img src=\"img/1.jpg\"></img>"
                + "</body></html>";

        Document doc = Jsoup.parse(html);

        // 获取标签
        //Elements links = doc.select("a");

        // 获取带有指定属性的标签
        Elements links = doc.select("img[src]");



        // 遍历标签并获取属性值
        for (Element link : links) {
            String url = link.attr("src");
            System.out.println("链接:" + url);
        }

输出

链接:img/1.jpg

java中Document获取HTML字符串中的每一个标签的每个属性

		String html = "<html><head><title>高克莱的一段html</title></head>"
                    + "<body><h1>这是一段html</h1>"
                    + "<p>点击网站名称访问网页</p>"
                    + "<a href=\"https://www.baidu.com\">百度</a>"
                    + "<a href=\"https://www.taobao.com\">淘宝</a>"
                    + "<img src=\"img/1.jpg\"></img>"
                    + "</body></html>";
        
        Document doc = Jsoup.parse(html);

        // 获取所有标签
        Elements tags = doc.getAllElements();
        
        // 遍历每个标签
        for (Element tag : tags) {
            System.out.println("Tag name: " + tag.tagName());
            
            // 获取每个标签的属性
            for (org.jsoup.nodes.Attribute attribute : tag.attributes()) {
                System.out.println("Attribute: " + attribute.getKey() + " = " + attribute.getValue());
            }
        }

输出

Tag name: #root
Tag name: html
Tag name: head
Tag name: title
Tag name: body
Tag name: h1
Tag name: p
Tag name: a
Attribute: href = https://www.baidu.com
Tag name: a
Attribute: href = https://www.taobao.com
Tag name: img
Attribute: src = img/1.jpg

引用的包

org.jsoup.nodes.Document;
org.jsoup.Jsoup;
org.jsoup.select.Elements;
org.jsoup.nodes.Element;
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值