python scrapy 爬取bing的背景圖片

最近看了下python,就想着獲取下bing的背景圖片,天天定時爬取,保存到本地,能夠作背景圖片用。 也在網上看了一些其餘的例子。就本身動手寫了一個小的爬圖片的python腳本。html

scrapy安裝

安裝是參照官網http://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/tutorial.html 安裝完成,本人的系統是ubuntu,因此按照ubuntu系統來安裝的,創建一個scrapy項目。 實現步驟: 1.是寫的根據url獲取到response body內容來解析出來的圖片地址,正則寫的很差(我的感受)。 2.獲取圖片的流保存到本地文件目錄python

# -*- coding: utf-8 -*-
import scrapy as sc
import os
import re
import cookielib
import urllib2


def get_file(url):
    try:
        cj = cookielib.LWPCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        urllib2.install_opener(opener)
        req = urllib2.Request(url)
        operate = opener.open(req)
        data = operate.read()
        return data
    except BaseException, e:
        print e
        return None


class ExampleSpider(sc.Spider):

    name = "bing"
    allowed_domains = ["cn.bing.com"]
    start_urls = (
        "http://cn.bing.com/",
    )

    def parse(self, response):
        bg = re.compile("g_img=\{url:..(http:.*)\",id:")
        path = "/home/zooy/Pictures/bing"
        if not os.path.exists(path):
            os.makedirs(path)

        url = bg.search(response.body).groups()[0]
        file_path = path + "/" + url.split('/')[-1]
        if not os.path.isfile(file_path):
            with open(path + "/" + url.split('/')[-1], "wb") as f:
                f.write(get_file(url))
                f.flush()
                f.close()

3.經過crontab 定義了一個定時,天天執行一下這個程序 sh腳本以下:ubuntu

#! /bin/sh
export PATH=$PATH:/usr/local/bin
cd /home/zooy/workcode/tutorial
nohup scrapy crawl bing >> bing.log 2>&1 &

如今天天都會去cn.bing.com去抓取一張圖片到本地來。cookie