直接上代码
import os.path
import urllib
from urllib.request import urlopen, urlretrieve
from urllib.parse import unquote
from apscheduler.triggers.cron import CronTrigger
from apscheduler.schedulers.blocking import BlockingScheduler
from bs4 import BeautifulSoup
from datetime import datetime
import re
bing_url = 'https://cn.bing.com/'
download_dir = 'C:\\Users\\xianghua\\Pictures\\Saved Pictures\\'
def get_html():
html = urlopen(bing_url)
bing_html = BeautifulSoup(html, 'html.parser')
return bing_html
def get_image_url(bing_html):
dic_style = bing_html.find('div', {'class': 'hpapp'}). \
find('div', {'class': 'hp_body'}). \
find('div', {'class': 'img_cont'}).attrs['style']
image_path = dic_style[(dic_style.index('(') + 1): dic_style.index(')')]
print(bing_url + image_path)
return bing_url + image_path
def get_filename(bing_html):
filename_href = bing_html.find('div', {'class': 'hpapp'}). \
find('div', {'class': 'hp_body'}). \
find('div', {'class': 'bottom_row'}). \
find('div', {'class': 'icon_text'}). \
find('a', href=re.compile('^(/search)')).attrs['href']
filename = filename_href[(filename_href.index('=') + 1): filename_href.index('&')]
name = unquote(filename, encoding='UTF-8')
print(name)
return name
def job():
print('Begin-----')
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
bing_html = get_html()
image_url = get_image_url(bing_html)
filename = get_filename(bing_html)
dir = download_dir + filename + '.jpg';
print(dir)
if not os.path.exists(dir):
urllib.request.urlretrieve(image_url, dir)
print('downloading......OK')
print('-----END')
c1 = CronTrigger(day_of_week='0-6', hour=11, minute=30, second=00)
if __name__ == '__main__':
job()