Bing背景图片获取代码

当我们使用微软的Bing的时候,会发现每天背景图片都是不一样的,但每张都很漂亮。鉴于最近在学习python,就萌生了获取每日Bing图片的想法,代码取自网上,我只是做了分析。

工作步骤:

1.取得Bing的response,分析一下Bing主页的源代码,有var g_img={url:’/fd/hpk2/ShuBrocade_ZH- CN760216482.jpg’,id:’bgDiv’,d:200,cN:’_SS’,crN:’bIm’,hash:’648′};sc_bgL(),在这里就是需要取得背景图片的地方。因为整个源代码只有这一处,所以可以用index(‘ ‘g_img={url:’)的方法去过滤背景图片的地址:content = urllib.urlopen(‘http://cn.bing.com/’).read()

tempStr = content[content.index(‘g_img={url:’)+12 : len(content)]

tempStr = tempStr[0 : tempStr.index(‘,id:’)-1]

tempStr = tempStr.replace(‘\’, ”)

bgImageUrl = ‘http://cn.bing.com’+tempStr

2. 下载图片的时候,使用urlretrieve(url, filename=None, reporthook=None, data =None)

3. 使用win32gui.SystemParametersInfo(Action, Param, WinIni)

#!/usr/bin/env python

#coding=utf-8

import os

import sys

import random

import urllib

import win32gui

import win32con

import Image

class Bing:

def __init__(self):

self.content = urllib.urlopen("http://cn.bing.com/").read()

self.bgImageUrl = ''

self.localFileName = ''

self.localBMPFileName = ''

def parseImageURL(self):

tempStr = self.content[self.content.index('g_img={url:')+12 : len(self.content)]

tempStr = tempStr[0 : tempStr.index(',id:')-1]

tempStr = tempStr.replace('\', '')

self.bgImageUrl = 'http://cn.bing.com' + tempStr

#only use for generate file name in local

def createLocalFileName(self):

randomStr = ''.join(random.sample(['a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], 6)).replace(" ", "")

self.localFileName = "D:/Bing/" + randomStr + ".jpg"

self.localBMPFileName = "D:/Bing/" + randomStr + ".bmp"

def downloadImage(self):

if self.bgImageUrl == "":

self.parseImageURL()

if self.localFileName == "":

self.createLocalFileName()

data = urllib.urlretrieve(self.bgImageUrl, self.localFileName)

def updateBGImage(self):

img = Image.open(self.localFileName)

img.save(self.localBMPFileName)

os.remove(self.localFileName)

win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, self.localBMPFileName, 0)

if __name__ == '__main__'== "__main__":

bing = Bing()

bing.downloadImage()

bing.updateBGImage()

顺便测试下bing图片是否可以外链:

09-11-22必应中国背景图一枚

link

评论

Popular Posts

《小狗钱钱》[德] 博多·舍费尔

《活法》作者:[日]稻盛和夫 pdf下载

一些有意思的网站和贴子

槭树下的家

IGN评选的史上TOP100游戏(2018版)

麦当劳免费Wifi帐号密码及连接设置

Re:从零开始的异世界生活 (2016)

人类的十个有趣心理效应

Tommai mai rub sak tee - Lydia