获取Bing主页的背景图片

来源:互联网 发布:网络电缆 编辑:程序博客网 时间:2024/06/06 18:57

一直对爬虫比较感兴趣,但是一直没有深入学习,浮于表面,每次有使用需求,就写一个,写完就完,没有总结过,也没有继续深入学习。
但是,作为一个奔三的程序员菜鸟,还是先不要自暴自弃,以后自爆的机会还很多~.~

这次做的是一个简单的爬虫,功能是获取Bing主页(http://cn.bing.com/)上的背景图。
开始尝试右键有没有另存为,发现没有,网上有的兄弟说在IE下打开可以右键保存,但是也没有。所以就想着用点高科技~~

思路:
爬去特定资源,当然要先分析页面了,我们要找的是背景图,所以首先想到的是“background”,查看网页源代码,搜索关键词,我们发现会有很多结果,而且有“background-image”这样可疑的字样,它后面还跟着url,这就更可疑了。我们尝试访问,看看具体是什么东西(这些url开头没有www,当然需要加上Bing的主页网址啦)。访问之后大家可以看到,这些都是图片资源,其中就有我们想要的背景图,那么接下来就是怎么获取的问题了。
源代码中查询背景图资源
既然找到了资源地址,接下来只需要将资源地址取出来,然后下载。取出来的过程就是通过字符串的操作将完整的url拼出来,然后将该地址下的内容下载下来。

思路就是这样,下面贴一些代码

public class SpiderUtil {    public static String getPicUrl(String content) throws IOException {        String url = "";        String[] ss = content.split("g_img=\\{url: \"");        url = ss[1].substring(0, ss[1].indexOf("\""));        return url;    }    public static String getFileName() {        Date date = new Date();        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        String format = sdf.format(date);        format = format.replaceAll("-", "");        String name = format + ".jpg";        return name;    }}

getPicUrl(String content)方法就是在网页中获取背景图的url,其中content指的就是网页代码,获取方法很简单,如下:

public Document getHtml(String url) throws IOException {        Connection conn = Jsoup.connect(url);        Document doc = conn.get();        return doc;    }

我这里爬虫用的主要就是jsoup,版本是1.10。document.html()返回的就是上文需要的content。

获取到url之后就要下载了

public void downloadPic(String url, String path) throws IOException {        Connection conn = Jsoup.connect(url);        Response resp = conn.ignoreContentType(true).execute();        FileUtil.write2File(resp, path);    }

方法中的url指的是图片的url,path指的是图片下载存放位置。
write2File方法代码如下:

    public static void write2File(String content, String path) throws IOException {        write2File(content.getBytes(), new File(path));    }    public static void write2File(Response resp, String path) throws IOException {        write2File(resp.bodyAsBytes(), new File(path));    }    public static void write2File(byte[] bytes, File file) throws IOException {        createFile(file);        FileOutputStream fos = new FileOutputStream(file);        fos.write(bytes);        fos.flush();        fos.close();    }    public static void createFile(File file) throws IOException {        if (!file.exists())            file.createNewFile();    }

这样整个流程就结束了。

小菜鸟上路啦,请各位指教~.~

原创粉丝点击