import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//获取logo图片 一些大型网址可以通过url+/favicon.ico
//比如:https://www.qq.com/favicon.ico 这种就存在一个问题,有些网址是没有配置,就获取不到!
//通过url解析网址title和logo
public Map<String,String> getUrlTilte(String url){
String tilte="";
Map<String,String> map=new HashMap<String,String>();
try {
//还是一样先从一个URL加载一个Document对象。
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("head");
Elements titlelinks=links.get(0).select("title");
tilte=titlelinks.get(0).text();
log.info("tilte={}",tilte);
map.put("tilte",tilte);
Elements imgs = doc.select("img");
//获取网址第一张图片
Elements titlelink=imgs.get(0).select("img");
String logo="";
String img=titlelink.get(0).toString();
Pattern p_image;
Matcher m_image;
List<String> pics = new ArrayList<String>();
String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
m_image = p_image.matcher(img);
while (m_image.find()) {
img = img + "," + m_image.group();
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
while (m.find()) {
logo=m.group(1);
}
}
map.put("logo",logo);
log.info("logo={}",logo);
}catch(Exception e) {
log.error("通过url={} 网址解析title和logo 异常:",url,e);
e.printStackTrace();
}
return map;
}
如果你是湖南的 欢迎加入 湖南人在深圳-Java群:557651502