分享一个Python实现的Bing图片下载器。下载首页图片并保存到到当前目录。其中用到了正则库re以及Request库。
大致流程如下:
1、Request抓取首页数据
2、re正则匹配首页图片URL
3、再次使用Request下载图片数据
源码:
# --*-- encoding: UTF-8 --*--
"""
bingloader.py
下载Bing.com首页图片
"""
import re
import sys
import os
import requests
# 解析获取Bing首页
url = ‘http://cn.bing.com/‘
print("Request Bing.com")
bingweb = requests.get(url=url)
f = open(‘test.html‘,‘w‘)
f.write(bingweb.text)
f.close()
# 搜索图片关键字
pattern = r‘g_img={url:\‘(http.*jpg)\‘,id:\‘bgDiv\‘,‘
m = re.search(pattern, bingweb.text)
if m:
picurl = m.group(1)
print("Picture url:\n{0}".format(picurl))
else:
print("Not Found picture url.")
sys.exit(-1)
filename = os.path.basename(picurl)
print(‘File name:%s‘ % filename)
if os.path.isfile(filename):
print("The Picture [%s]‘ has download." % filename)
raw_input("Press any key.")
sys.exit(0)
# 下载图片数据
print("Download Picture...")
data = requests.get(picurl,stream=True)
with open(filename, ‘wb‘) as picfile:
for chunk in data.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
picfile.write(chunk)
picfile.flush()
picfile.close()
print("Finished.")
raw_input("Press any key.")