在做项目时候遇到一个需求,后台添加微信公众号上面的文章时候能自动获取到这篇文章的标题、发布时间、封面图片,这样就不用手动去添加太多的信息,只需要一个url就够了。所以用jsoup做了一个简单的爬虫,根据文章的url获取这些信息。
原理
封面图片:
随便选择一个微信公众号,例如:
如图上所示就是文章的封面图片,这些封面图片大多在原文里是有的。但是,像上面这两篇文章,原文里是没有封面图的。但是在文章源码下面的script里藏着封面图片的url:
而且“msg_cdn_url"是唯一字符串,所以,获取封面图片就是要定位到“msg_cdn_url"就可以了。代码见后面。
文章发表时间:
点开文章进去是没有发表时间的,其实是隐藏在这图上这里,点一下就会变成年月日,所以无法直接通过页面定位到这里获取时间。
但是既然点一下就能变成时间那说明时间是有的,只是在script里面,接下来就可以在源码里用crtl+F查找时间“-04-28”,定位到时间所在的script位置。
经过观察可以发现这里其实没法直接定位,所以得用点间接方法。循环遍历所有的script标签,查看里面是否包含字符串"document.getElementById(“publish_time”)",如果有,则在这个script里定位到“s="”,这样就找到了时间的位置。
其他像“作者”、“标题”那些比较简单,直接见代码
import java.io.IOException;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public class HandleUrl {//获取文章封面图片public static String getCoverUrl(String informationUrl) throws IOException {String picUrl = null;int flag;Document doc = Jsoup.connect(informationUrl).timeout(3000).get();String htmlString=doc.toString();flag=htmlString.indexOf("msg_cdn_url");while(htmlString.charAt(flag)!='\"'){flag++;}int beginIndex=++flag;while(htmlString.charAt(flag)!='\"')flag++;int endIndex=--flag;picUrl=htmlString.substring(beginIndex,endIndex);return picUrl;}//获取文章作者public static String getAuthor(String informationUrl) throws IOException {Document doc = Jsoup.connect(informationUrl).timeout(3000).get();Element authors = doc.getElementById("js_name");String author = authors.text();return author;}//获取文章时间public static String getTime(String informationUrl) throws IOException {String time=null;Document doc = Jsoup.connect(informationUrl).timeout(3000).get();Elements scripts = doc.select("script");for (Element script : scripts) {String html = script.html();if (html.contains("document.getElementById(\"publish_time\")")) {int fromIndex = html.indexOf("s=\"");time=html.substring(fromIndex+3,fromIndex+13);return time;}}return time;}//获取文章标题public static String getTitle(String informationUrl) throws IOException {Document doc = Jsoup.connect(informationUrl).timeout(3000).get();Elements titles = doc.getElementsByClass("rich_media_title");String title = titles.text();return title;}public static void main(String[] args) throws IOException {String url="https://mp./s/gcG6PnYwJUDabdYYe_snYw";System.out.println(getTime(url));System.out.println(getTitle(url));System.out.println(getAuthor(url));}}