
本文首發(fā)于個人博客。
幾年前寫過一篇用 Python 下載每日必應(yīng)背景圖的方法,不過由于必應(yīng)網(wǎng)站更新,之前的方法失效了。
這次抽空更新了一下。
適用的 Python 的版本為 Python3 及以上。
因為必應(yīng)官方限制,只能下載最近 8 張圖。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- author: uncoverman-*-
# Python3 抓取 bing 主頁所有背景圖片
import urllib.request,re,sys,os
def get_bing_backphoto():
if (os.path.exists('photos')== False):
os.mkdir('photos')
for i in range(0,8):
url = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx='+str(i)+'&n=1&nc=1361089515117&FORM=HYLH1'
html = urllib.request.urlopen(url).read()
if html == 'null':
print( 'open & read bing error!')
sys.exit(-1)
html = html.decode('utf-8')
reg = re.compile('"url":"(.*?)","urlbase"',re.S)
text = re.findall(reg,html)
for imgurl in text :
# http://cn.bing.com/th?id=OHR.CorsicaHeart_ZH-CN2795615037_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
bingimgurl = 'http://cn.bing.com'+imgurl
right = imgurl.index('&')
name = imgurl.replace(imgurl[right:],'')
left = name.index('.')
imgname = name.replace(name[:left+1],'')
savepath = 'photos/'+ imgname
urllib.request.urlretrieve(bingimgurl, savepath)
print (imgname + ' save success!')
get_bing_backphoto()
使用方法:將以上代碼復(fù)制到后綴為.py的文件,然后運行.py的文件即可。