python爬虫(22)获取必应主页的背景当壁纸

前言

虽然微软一直推的必应浏览器不怎么用,但是发现它主页的图片确实精致的,那把它拿下来当作壁纸怎么样。
今天来小小的实践一下

环境

操作系统:Ubuntu18.04
编程语言:python3.6

获取壁纸

网页分析

打开必应主页https://www.bing.com,并点击国际版(为什么不点国内版,国内版找不到加载图片的内容,直接从网页上找费劲),然后打开F12工具

然后发现有这么一条内容,点开发现它加载的内容,返回的内容(也就是response)是一个json网页(为啥我知道这里,慢慢找的~)复制这个地址:https://www.bing.com/HPImageArchive.aspx?format=hp&idx=0&n=1&nc=1564646574878&pid=hp&video=1&quiz=1&og=1&IG=60023099F29847979DA2DC27F37CF38D&IID=SERP.1050

单独打开看一下,确实是一串json数据,但是这个看着不是特别舒服,将上面的网址format=hp换成format=js然后打开这个网址,看着有点顺眼了

实际上呢,这个网址不用那么长,只用它就行了:https://www.bing.com/HPImageArchive.aspx?format=js&n=1
然后找到[images][0][url],将其拼接一下,然后就有了这个图片了
https://www.bing.com/th?id=OHR.LavaFlows_EN-US3642057889_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp%22

代码

	json_url="https://www.bing.com/HPImageArchive.aspx?format=js&n=1"#where to get the json file
	bing_url="https://www.bing.com"#bing.com main domain
	if not os.path.exists(picture):
		#get the json file and hide the file
		urllib.request.urlretrieve(json_url,bing_json_file)
		#open the file and import json string
		with open(bing_json_file,"r",encoding='utf-8') as f:
			bing_json=json.load(f)
		url_append=bing_json['images'][0]['url']
		url=bing_url+url_append
		#get picture
		urllib.request.urlretrieve(url,picture)

这样就简单的把图片下载到本地了

设置壁纸

Ubuntu系统可以通过命令行来设置壁纸

下面的命令设置背景为空

gsettings set org.gnome.desktop.background picture-uri none

其中none可以使用本地图片路径,这样就可以通过命令行来设置背景图片了

gsettings set org.gnome.desktop.background picture-uri "file:/home/user/Pictures/Bing/2019-08-01.jpg"

其他

多获取几张图片

获取json数据的网址,后面的n=1可以替换,最大n=7这样就能得到最近7天必应主页用过的壁纸了

https://www.bing.com/HPImageArchive.aspx?format=js&n=7

随机得到一张图片

import os,random
return random.choice(os.listdir('/home/your-name/Pictures/Wallpapers'))

定时更换图片

使用contrab 设置一个定时命令,自动每隔一段时间更换壁纸

代码

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Date    : 2019-08-02 14:58:19
# @Author  : Jimy_Fengqi (jmps515@163.com)
# @Link    : https://blog.csdn.net/qiqiyingse
# @Github  : https://github.com/JimyFengqi
# @Version : V1.0
import json
import os,random
import urllib.request
import datetime


HOME=os.path.expandvars('$HOME')+"/"#user home directory
pic_dir=HOME+"Pictures/Bing"#default dir
isdelete=True
delete_time=30

def load_config():#the load config function
	global HOME
	global pic_dir
	config_dir=HOME+".config/Bing"
	json_file=config_dir+"/"+"config.json"
	init_config={'Bing':{'dir':pic_dir,'delete':'True','time':'30','version':'1.0'}}
	if not os.path.exists(config_dir):
		os.makedirs(config_dir)
	if not os.path.exists(json_file):
		with open(json_file,'w',encoding='utf-8') as f:
			json.dump(init_config,f,ensure_ascii=False,indent=4)
	with open (json_file,'r',encoding='utf-8') as f:
		config_json=json.load(f)
	pic_dir=config_json['Bing']['dir']+'/'
	isdelete=config_json['Bing']['delete']
	delete_time=config_json['Bing']['time']
	if not os.path.exists(pic_dir):
		os.makedirs(pic_dir)

def download_and_apply():
	global HOME
	global pic_dir
	global delete_time
	date=datetime.datetime.now().strftime('%Y%m%d')
	today_picture=pic_dir+date+".jpg"
	yesterday_pic = pic_dir+str(int(date)-1)+".jpg"
	bing_json_file=HOME+".bing.json"
	json_url="https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=7"#where to get the json file
	bing_url="https://www.bing.com"#bing.com main domain

	print('当前目录有照片:',os.listdir(pic_dir))
	pic_num = len(os.listdir(pic_dir))
	if not os.path.exists(today_picture):
		if not os.path.exists(yesterday_pic) or pic_num < 7:#只有初始化或者最近两天照片都不在或者操作失误删除照片小于7张,才需要一次下载7张
			print('今天是%s,全部初始化!'%  date)
			#get the json file and hide the file
			urllib.request.urlretrieve(json_url,bing_json_file)
			#open the file and import json string
			with open(bing_json_file,"r",encoding='utf-8') as f:
				bing_json=json.load(f)
			url_append=bing_json['images']
			for image in url_append:
				imgurl = bing_url+image['url']
				imgname = pic_dir+image['startdate']+'.jpg'

				#get picture
				urllib.request.urlretrieve(imgurl,imgname)
		else:
			print('今天是%s,今天的图片还没有更新!'%  date)
			urllib.request.urlretrieve(json_url,bing_json_file)
			#open the file and import json string
			with open(bing_json_file,"r",encoding='utf-8') as f:
				bing_json=json.load(f)
			url_append=bing_json['images'][0]['url']
			imaurl=bing_url+url_append
			imgname = pic_dir+bing_json['images'][0]['startdate']+'.jpg'
			print('开始下载【%s】,原地址是:%s' % (imgname,imaurl))
			#get picture
			urllib.request.urlretrieve(imaurl,imgname)		
	chooseImage= pic_dir+random.choice(os.listdir(pic_dir))
	#change screen saver
	cmd="gsettings set org.gnome.desktop.background picture-uri file:"+chooseImage
	print('选择[%s]作为壁纸'% chooseImage )
	os.system(cmd)

def del_old_pic():
	global isdelete
	global delete_time
	global pic_dir
	day_s=datetime.datetime.now()-datetime.timedelta(days = delete_time)
	day=day_s.strftime('%Y%m%d')
	pic_del=pic_dir+day+".jpg"
	if isdelete == True:
		print('应该删除%s的照片:%s'% (day,pic_del))
		if os.path.exists(pic_del):
			os.remove(pic_del)
			print('已经删除%s的照片:%s'% (day,pic_del))

if __name__=='__main__':
	load_config()
	download_and_apply()
	del_old_pic()

 

posted @ 2019-08-01 16:29  枫奇丶宛南  阅读(117)  评论(0)    收藏  举报