来源 | Python与数据分析
Unsplash是个高清摄影图片的网站,里面的照片非常精美,分辨率也很高,最重要的是,所有的照片都没有版权,无须向原作者申请授权,即可任意使用。
最近闲暇的时候写了个爬虫爬了下Unsplash上的那些高赞的壁纸。爬虫原理非常简单,就是爬取所有的壁纸,然后筛选那些赞数最高的图片。
第一步我们爬取Unsplash所有的壁纸图片信息,并存入MongoDB,代码如下
def get_image_by_page(page_no):
url = "https://unsplash.com/napi/collections/1065976/photos?page={}&per_page=10&order_by=latest&share_key=a4a197fc196734b74c9d87e48cc86838".format(page_no)
r = requests.get(url, verify=False)
data = r.json()
return datadef get_images():
page_no = 1
client = pymongo.MongoClient()
db = client["unsplash"]
while True:
result = get_image_by_page(page_no)
if len(result) == 0:
break
db.wallpaper.insert_many(result)
print(page_no)
page_no += 1
time.sleep(10)爬下来的数据里面包含了几个重要的字段。
我们最关心的就是likes这个字段,这个里面存了图片的赞数,后续我们筛选高赞图片的时候会用到。
还有两个字段分别是width和height,这是图片的宽度和高度,因为我们这里关注的是桌面壁纸,所以只关心宽度大于高度的那些壁纸。
爬完图片信息后,接下来我们从数据库筛选高赞图片,代码如下
def get_top_liked_images():
client = pymongo.MongoClient()
db = client["unsplash"]
cursor = db.wallpaper.aggregate([
{"$match": {"likes": {"$gte": 1000}}}
]) path = os.path.dirname(__file__)
path = os.path.join(path, "wallpaper")
for item in cursor:
url = item["urls"]["raw"]
width = item["width"]
height = item["height"]
if width <= height:
continue
r = requests.get(url, verify=False)
filename = "{}.jpg".format(int(time.time()))
filepath = os.path.join(path, filename)
with open(filepath, "wb") as f:
f.write(r.content)
print(filepath)
time.sleep(10)这里我们会根据图片信息里的URL去下载图片。需要注意的是,如果过于频繁的爬取Unsplash,会导致爬虫被封,所以这里每次下载完都会睡个10秒钟。