如何使用Java中的Regex获取页面元数据(标题,描述,图像),例如Facebook附加网址 [英] How to get page meta (title, description, images) like facebook attach url using Regex in java

查看:56
本文介绍了如何使用Java中的Regex获取页面元数据(标题,描述,图像),例如Facebook附加网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在.java中使用Regex获取页面元数据(标题,描述,图像),例如Facebook附加网址

How to get page meta (title, description, images) like facebook attach url using Regex in .java

推荐答案

下面是一个片段,它读取网页并构建一小段HTML,以显示Open Graph图像,并在图像的右侧包裹标题.如果缺少OG标签,则只能使用html标题,因此它可以代表所有网页.

Here's a snippet that reads a web page and builds a little chunk of HTML that will display the Open Graph image, and Title to the right wrapping around the image. It falls back to using just html title if OG tags are missing, so it can work to represent all web pages.

public static String parsePageHeaderInfo(String urlStr) throws Exception {

    StringBuilder sb = new StringBuilder();
    Connection con = Jsoup.connect(urlStr);

    /* this browseragant thing is important to trick servers into sending us the LARGEST versions of the images */
    con.userAgent(Constants.BROWSER_USER_AGENT);
    Document doc = con.get();

    String text = null;
    Elements metaOgTitle = doc.select("meta[property=og:title]");
    if (metaOgTitle!=null) {
        text = metaOgTitle.attr("content");
    }
    else {
        text = doc.title();
    }

    String imageUrl = null;
    Elements metaOgImage = doc.select("meta[property=og:image]");
    if (metaOgImage!=null) {
        imageUrl = metaOgImage.attr("content");
    }

    if (imageUrl!=null) {
        sb.append("<img src='");
        sb.append(imageUrl);
        sb.append("' align='left' hspace='12' vspace='12' width='150px'>");
    }

    if (text!=null) {
        sb.append(text);
    }

    return sb.toString();       
}

这篇关于如何使用Java中的Regex获取页面元数据(标题,描述,图像),例如Facebook附加网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆