Python 輕松爬取上千張小姐姐圖片
廢話不多說(shuō),咱們直接上最終的效果圖
圖片
圖片
我們獲取圖片的目標(biāo)地址是 360 壁紙庫(kù),網(wǎng)上有大神已經(jīng)做過(guò)一波分析了,我們直接拿來(lái)使用
美圖獲取
我們首先獲取壁紙分類(lèi)信息
先使用 postman 調(diào)用,查看響應(yīng)數(shù)據(jù)情況
圖片
使用代碼保存分類(lèi)信息
import requests
import json
import time
category = requests.get("http://cdn.apc.#/index.php?c=WallPaper&a=getAllCategoriesV2&from=360chrome")
category_list = category.json()['data']
# 保存category到j(luò)son文件
category_list
with open("categoty.json",'w', encoding='utf-8') as file_obj:
json.dump(category_list, file_obj, ensure_ascii=False, indent=4)
接下來(lái)再看下具體的獲取圖片的接口情況
圖片
同樣可以根據(jù)響應(yīng)信息,來(lái)編寫(xiě)解析代碼
def get_pic(categoty, count):
for i in range(1, 100):
pic_list = []
pic_url = "http://wallpaper.apc.#/index.php?c=WallPaper&a=getAppsByCategory&cid=%s&start=%s&count=%s&from=360chrome" % (categoty, str(i), count)
pic = requests.get(pic_url)
pic_data = pic.json()["data"]
if pic_data:
tmp = deal_pic_data(pic_data)
else:
break
time.sleep(5)
其中在函數(shù) deal_pic_data 當(dāng)中,我們調(diào)用了兩個(gè)子函數(shù),分別用來(lái)下載圖片和 tag 信息
def download_img(img_url, name):
print (img_url)
r = requests.get(img_url, stream=True)
print(r.status_code) # 返回狀態(tài)碼
if r.status_code == 200:
open("pic\\" + name + '_img.png', 'wb').write(r.content) # 將內(nèi)容寫(xiě)入圖片
print("done")
del r
def save_tag(tag, name):
print(tag)
with open("tag\\" + name + ".txt", "w") as f:
f.write(tag)
下圖即為爬取過(guò)程
圖片
最終我們?cè)诒镜鼐统晒Ρ4媪松锨埿〗憬阏掌?/p>
圖片
你以為這樣就結(jié)束了嗎,當(dāng)然沒(méi)有
制作網(wǎng)站
畢竟這么多的小姐姐,都在文件夾里是多么的不方便查看呀,我們做成 web 瀏覽起來(lái)是真的香!
我們先編寫(xiě) index 頁(yè)面的視圖函數(shù)
@app.route('/', methods=['GET', 'POST'])
def index():
pic_path = basedir + "\static\img\pic"
pic_list = os.listdir(pic_path)
seg = int(len(pic_list)/4)
data = []
socre = 5
for n in pic_list[:seg]:
tmp_data = []
pic_url = random.choice(pic_list)
tmp_data.append(r"\static\img\pic\\" + pic_url)
tmp_data.append(pic_list.index(n))
data.append(tmp_data)
return render_template('index.html', data=data, score=socre)
我們從本地文件夾中拿到小姐姐圖片,然后組裝成需要的數(shù)據(jù)格式,傳遞給前端
對(duì)于 index.html 代碼
<section id="gallery-wrapper">
{% for p in data %}
<article class="white-panel">
<img class="thumb" data-original="{{ p[0] }}">
<h1><a href="{{ url_for('nvshen', id=p[1]) }}" title="去設(shè)置" target="_blank">喜歡??</a>
</h1>
</article>
{% endfor %}
</section>
在拿到后端傳遞的數(shù)據(jù)后,依次展示在 section 標(biāo)簽中
接下來(lái)是詳情頁(yè)面
@app.route('/nvshen/<id>/', methods=['GET', 'POST'])
def nvshen(id):
pic_path = basedir + "\static\img\pic"
pic_list = os.listdir(pic_path)
pic_url = r"\static\img\pic\\" + pic_list[int(id)]
data = []
score_pic_path = r"static\img\pic\\" + pic_list[int(id)]
gender, age, female_score, male_score, emotion_data = fire_score(score_pic_path)
data.append('性別: %s' % gender)
data.append('年齡: %s' % age)
data.append('顏值評(píng)分: %s' % female_score)
data.append('情緒: %s' % emotion_data)
return render_template('nvshen.html', nvshenid=id, main_url=pic_url, data_list=data, user_score=5)
我這里調(diào)用了曠視 Face++ 的人臉識(shí)別接口,自動(dòng)返回不同小姐姐的顏值信息
再來(lái)看看前端的 HTML 代碼
<div align="center">
<section style="width: 100%">
<img src="{{ main_url }}" width="40%" height="20%">
<div id="starBg1" class="">
<input type="button" name="設(shè)置為桌面" value="設(shè)置為桌面" onclick="setWallpaper('{{ main_url }}')" id="btn">
</div>
</section>
</div>
<section id="gallery-wrapper">
{% for d in data_list %}
<article class="white-panel">
<h1><a href="#">{{ d }}</a>
</h1>
</article>
{% endfor %}
</section>
分別展示設(shè)置桌面按鈕和顏值信息卡片
最后我們?cè)賮?lái)看看如何設(shè)置桌面壁紙
可以看到在上面的代碼中,調(diào)用了一個(gè) setWallpaper 函數(shù)
<script>
function setWallpaper(pic) {
var filename;
if (pic.indexOf("\\") > 0)//如果包含有"/"號(hào) 從最后一個(gè)"/"號(hào)+1的位置開(kāi)始截取字符串
{
filename = pic.substring(pic.lastIndexOf("\\") + 1, pic.length);
}
else {
filename = pic;
}
var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open('GET', '/setwallpaper/' + filename, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function (ev) {
if (this.status === 200) {
if (this.response['end'] === true) {
flag = false;
}
var mydata = this.response['msg'];
//console.log(mydata[1][2]);
} else if (this.status === 422) {
console.log("Set Wallpaper error");
}
};
xhr.send();
}
</script>
我們這里調(diào)用了后端的 setwallpaper 接口
@app.route("/setwallpaper/<pic>")
def setWallpaperView(pic):
try:
pic_path = basedir + "\static\img\pic\\" + pic
result = setWallpaper(pic_path)
return jsonify({"msg": "OK"}), 200
except Exception as e:
return jsonify({"msg": "ERROR"}), 422
import win32api
import win32gui
import win32con
def setWallpaper(imagepath):
k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 2拉伸,0居中,6適應(yīng),10填充,0平鋪
win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0") # 1表示平鋪,拉伸居中等都是0
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,imagepath, 1+2)
return "Set OK"
通過(guò)后端代碼,來(lái)進(jìn)行桌面壁紙的設(shè)置,設(shè)置壁紙采用的是直接通過(guò) win32gui 改寫(xiě)注冊(cè)表信息
整體代碼下來(lái),我們主要用到了 Python 爬蟲(chóng)簡(jiǎn)單技術(shù),F(xiàn)lask 的簡(jiǎn)單應(yīng)用以及部分 HTML&JavaScript 技術(shù),技術(shù)棧還是比較簡(jiǎn)單的,喜歡的小伙伴一起來(lái)實(shí)現(xiàn)下吧