py小教学:今天偶然知道一个叫花瓣的网站,里面好多高清好图。于是想批量的下载一下里面的图片。
据说py很简单于是百度了一下,py的爬虫,爬取花瓣的图片。下面分享一下py脚本,全程ctrl+c和ctrl+v,请勿见笑。
import requests
import re
import os.path
if __name__ == '__main__':
# 获取html
req = requests.get("http://huaban.com/favorite/beauty/")
htmlPage = req.content
# 正则匹配到标签(需要的图片标签)
prog = re.compile(r'app\.page\["pins"\].*')
appPins = re.findall(prog, htmlPage.decode('utf-8'))
# 解析json所需的一些小配置
# 将js中的null定义为Python中的None
null = None
true = True
# 解析结果
result = eval(appPins[0][19:-1])
# 需要的所有图片链接
images = []
for i in result:
# 自己组装json
info = {}
# 花瓣的图片的规则
info['id'] = str(i['pin_id'])
info['url'] = "http://img.hb.aicdn.com/" + i["file"]["key"] + "_fw658"
info['type'] = i["file"]["type"][6:]
images.append(info)
# 下载图片
for key, image in enumerate(images):
req = requests.get(image["url"])
imageName = os.path.join("C:\\pic", image["id"] + "." + image["type"])
with open(imageName, 'wb') as fp:
fp.write(req.content)