如何在.java中使用Regex获取像facebook这样的页面元素(标题,描述,图像)
小智 13
这是一个片段,它读取一个网页并构建一小部分HTML,它将显示Open Graph图像,右边的Title包围图像.如果缺少OG标签,它会回退到仅使用html标题,因此它可以表示所有网页.
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();
}
Run Code Online (Sandbox Code Playgroud)
正如Ishikawa Yoshi所提到的,使用JSoup
例:
Document doc = Jsoup.connect("http://example.com/").get()
for(Element meta : doc.select("meta")) {
System.out.println("Name: " + meta.attr("name") + " - Content: " + meta.attr("content"));
}
Run Code Online (Sandbox Code Playgroud)
这段代码未经测试,希望对此有所帮助.
使用RegEx来抓取文档是一个坏主意,请在Coding Horror上阅读