尚学堂学姐笔记:Jsoup示例——提取URL中的图像和元数据

        今天的学姐笔记会和大家分享提取URL中图像的技巧,这样可以方便大家在制作网页时调用其他网页的资源,提高网页数据之间的相关性。以下案例由尚学堂李老师提供,希望对大家有所帮助。


        在这个例子中,我们将提取并打印给定URL的所有图像信息。 要做到这一点,我们调用select()方法传递“"img[src~=(?i)\\.(png|jpe?g|gif)]"”正则表达式作为参数,以便它可以打印png,jpeg或gif类型的图像。

import org.jsoup.Jsoup;  
import org.jsoup.nodes.Document;  
import org.jsoup.nodes.Element;  
import org.jsoup.select.Elements;  
public class JsoupPrintImages {  
     public static void main( String[] args ) throws IOException{  
            Document doc = Jsoup.connect("http://www.yiibai.com").get();  
            Elements images = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");  
            for (Element image : images) {  
                System.out.println("src : " + image.attr("src"));  
                System.out.println("height : " + image.attr("height"));  
                System.out.println("width : " + image.attr("width"));  
                System.out.println("alt : " + image.attr("alt"));  
            }  

}  

`
Java
执行结果 -

... ...
Shell
自已编程运行试试吧!

        下面继续介绍在URL中提取元数据的方法。我们将打印一个URL的meta关键字和描述。要实现这个功能,需要调用Document类的select(),first(),get()和attr()方法。
如下代码实现

import java.io.IOException;  
import org.jsoup.Jsoup;  
import org.jsoup.nodes.Document;  
public class JsoupPrintMetadata {  
     public static void main( String[] args ) throws IOException{  
            Document doc = Jsoup.connect("http://www.yiibai.com").get();  

            String keywords = doc.select("meta[name=keywords]").first().attr("content");  
            System.out.println("Meta keyword : " + keywords);  
            String description = doc.select("meta[name=description]").get(0).attr("content");  
            System.out.println("Meta description : " + description);  
    }  
}  
`
Java
执行结果 -

... ...
Shell
运行结果还请大家亲自动手尝试哦!
        如果以上内容对你有所帮助,别忘了添加关注。每日编程技术持续更新!

转载于:https://my.oschina.net/u/3628059/blog/1504521

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值