前言
本月將更新八篇Python有趣系列文章。本系列通過多個有趣案例因妙,講解Python的玩法痰憎,其中包含如下內(nèi)容,一一推進(jìn)講解兰迫。
- 爬蟲
- 數(shù)據(jù)分析
- 機(jī)器學(xué)習(xí)
項(xiàng)目背景
最近知乎老是給我推送兩個問答信殊,一個是長得好看是種什么體驗(yàn)炬称?汁果,另一個是女朋友長得好看是怎樣的體驗(yàn)?所以玲躯,本文將講解如何爬取知乎這兩個問題的回答中的圖片据德,并通過百度人臉識別api進(jìn)行顏值打分,選取出知乎最美小姐姐跷车。整個項(xiàng)目流程如下圖所示:
網(wǎng)頁分析
首先棘利,我們打開一個話題他挎,通過F12查看团南,可以看到是一個異步加載的網(wǎng)頁锦庸,我們需要對其進(jìn)行找包位隶,如圖摧阅,這個包就是我們所需要的短蜕。
接著患雏,我們分析下這個url拾因,可以發(fā)現(xiàn)或渤,除了offset用于分頁系冗,questions后面的數(shù)字為不同問題的ID。之外薪鹦,其他url的參數(shù)都是固定的掌敬,所以我們只需要構(gòu)造這個url,不斷循環(huán)請求就好了池磁。
https://www.zhihu.com/api/v4/questions/29024583/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit=3&offset=3&platform=desktop&sort_by=default
返回的數(shù)據(jù)為json數(shù)據(jù)奔害,我們這里只是需要圖片,所以只提取用戶昵稱和內(nèi)容(昵稱用于圖片取名地熄,內(nèi)容中有圖片信息)华临。
圖片信息存在content字段中,我們通過正則表達(dá)式來進(jìn)行提取离斩。
爬蟲代碼
根據(jù)上面的思路银舱,我們編寫爬蟲代碼:
import requests
from lxml import etree
import json
import time
import re
headers = {
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
'cookie':''
}
def get_img(url):
res = requests.get(url,headers=headers)
i = 1
json_data = json.loads(res.text)
datas = json_data['data']
for data in datas:
id = data['author']['name']
content = data['content']
imgs = re.findall('img src="(.*?)"',content,re.S)
if len(imgs) == 0:
pass
else:
for img in imgs:
if 'jpg' in img:
res_1 = requests.get(img,headers=headers)
fp = open('row_img/' + id + '+' + str(i) + '.jpg','wb')
fp.write(res_1.content)
i = i + 1
print(id,img)
if __name__ == '__main__':
urls = ['https://www.zhihu.com/api/v4/questions/29024583/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit=5&offset={}&platform=desktop&sort_by=default'.format(str(i)) for i in range(0,25000,5)]
for url in urls:
get_img(url)
time.sleep(2)
這里cookie需要換成自己的瘪匿,我們圖片的命名為用戶昵稱+數(shù)字(由于一個回答可能有多個圖片),結(jié)果如圖寻馏,這樣棋弥,就解鎖了一份小姐姐圖片。
人臉識別API
由于爬取了圖片诚欠,有一些是沒人像顽染,有些是男的...而且是為了找到高顏值小姐姐,如果人工篩選費(fèi)事費(fèi)力轰绵,這里調(diào)用百度的人臉識別API粉寞,進(jìn)行圖片過濾和顏值打分,選出知乎最美小姐姐左腔。
首先唧垦,打開網(wǎng)址(http://ai.baidu.com/tech/face),登陸后立即使用液样,我們首先創(chuàng)建一個人臉識別的應(yīng)用振亮。api的使用說簡單很簡單(看文檔就好了),說難也很難(大家的閱讀能力在慢慢下降)鞭莽。首先坊秸,我們看著文檔(https://ai.baidu.com/docs#/Face-Detect-V3/top),一步步來澎怒。
接著我們通過API Key和Secret Key獲取token:
import requests
ak = ''
sk = ''
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(ak,sk)
res = requests.post(host)
print(res.text)
我們拿著token褒搔,來請求對應(yīng)的網(wǎng)頁就可以獲取圖片的內(nèi)容了。我們拿張超越妹妹的圖片做例子~
import base64
import json
token = ''
def get_img_base(file):
with open(file,'rb') as fp:
content = base64.b64encode(fp.read())
return content
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
request_url = request_url + "?access_token=" + token
params = {
'image':get_img_base('test.jpg'),
'image_type':'BASE64',
'face_field':'age,beauty,gender'
}
res = requests.post(request_url,data=params)
result = res.text
json_result = json.loads(result)
code = json_result['error_code']
gender = json_result['result']['face_list'][0]['gender']['type']
beauty = json_result['result']['face_list'][0]['beauty']
print(code,gender,beauty)
### result 0 female 76.25
這里的token為前面請求得到的喷面,params的參數(shù)中星瘾,圖片需要base64編碼~超越妹妹76.25,還算給力乖酬。
綜合使用
最后死相,我們逐一請求我們保存的圖片,過濾掉非人物以及男性圖片咬像,獲取小姐姐圖片的分?jǐn)?shù)(這里處理為1-10分)算撮,并分別存在不同的文件夾中。
import requests
import os
import base64
import json
import time
def get_img_base(file):
with open(file,'rb') as fp:
content = base64.b64encode(fp.read())
return content
file_path = 'row_img'
list_paths = os.listdir(file_path)
for list_path in list_paths:
img_path = file_path + '/' + list_path
# print(img_path)
token = '24.a2d7a4d09435e716cf1cb163f176cb12.2592000.1553929524.282335-15648650'
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
request_url = request_url + "?access_token=" + token
params = {
'image':get_img_base(img_path),
'image_type':'BASE64',
'face_field':'age,beauty,gender'
}
res = requests.post(request_url,data=params)
json_result = json.loads(res.text)
code = json_result['error_code']
if code == 222202:
continue
try:
gender = json_result['result']['face_list'][0]['gender']['type']
if gender == 'male':
continue
beauty = json_result['result']['face_list'][0]['beauty']
new_beauty = round(beauty/10,1)
print(img_path,new_beauty)
if new_beauty >= 8:
os.rename(os.path.join(file_path,list_path),os.path.join('8分',str(new_beauty) + '+' + list_path))
elif new_beauty >= 7:
os.rename(os.path.join(file_path,list_path),os.path.join('7分',str(new_beauty) + '+' + list_path))
elif new_beauty >= 6:
os.rename(os.path.join(file_path,list_path),os.path.join('6分',str(new_beauty) + '+' + list_path))
elif new_beauty >= 5:
os.rename(os.path.join(file_path,list_path),os.path.join('5分',str(new_beauty) + '+' + list_path))
else:
os.rename(os.path.join(file_path,list_path),os.path.join('其他分',str(new_beauty) + '+' + list_path))
time.sleep(1)
except KeyError:
pass
except TypeError:
pass
今日互動
代碼下載:公眾號后臺回復(fù)【知乎小姐姐】县昂,下載完整代碼肮柜。
留言打卡:說說自己做的最有趣的爬蟲項(xiàng)目吧。最近開始運(yùn)營社群倒彰,公眾號后臺回復(fù)【打卡】审洞,加入打卡學(xué)習(xí)群,2019年一起搞事情。