Python 抓取必应首页壁纸

#-*- coding: utf-8 -*-

import urllib2
import re
import time
import datetime

def save_img(img_url):
    img_name = img_url[img_url.rindex('/')+1:]
    img_data = urllib2.urlopen(img_url).read()
    f = open(img_name,'wb')
    f.write(img_data)
    f.close()
    print 'success saved image:',img_url

# 下载今日必应首页壁纸
def today_bingwallpaper():
    url = 'http://cn.bing.com'
    try:
        html = urllib2.urlopen(url).read()
        img_url = re.findall(r"g_img={url:'(.+?)'",html)[0]

        print img_url
        save_img(img_url)
    except:
        print 'failed'
# 下载今日前num天壁纸
def bingwallpaper_index(num):
    tn = time.time()
    url = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx=%d&n=1&nc=%d&pid=hp&scope=web&FORM=QBRE&video=1'%(num,int(tn))
    response = urllib2.urlopen(url).read()
    try:
        img_url = re.findall(r'"url":"(.+?)"',response)[0]
        save_img(img_url)
    except:
        print 'failed'

if __name__ == '__main__':
    # 下载今日必应首页壁纸
    today_bingwallpaper()
    # 下载近21天必应首页壁纸
    # for i in xrange(21):
    #     bingwallpaper_index(i)


你可能感兴趣的:(python,网络爬虫)