Python有趣|尋找知乎最美小姐姐

前言

本月將更新八篇Python有趣系列文章。本系列通過多個有趣案例,講解Python的玩法,其中包含如下內(nèi)容,一一推進講解。

  • 爬蟲
  • 數(shù)據(jù)分析
  • 機器學(xué)習(xí)
項目背景

最近知乎老是給我推送兩個問答,一個是長得好看是種什么體驗?,另一個是女朋友長得好看是怎樣的體驗?所以,本文將講解如何爬取知乎這兩個問題的回答中的圖片,并通過百度人臉識別api進行顏值打分,選取出知乎最美小姐姐。整個項目流程如下圖所示:

網(wǎng)頁分析

首先,我們打開一個話題,通過F12查看,可以看到是一個異步加載的網(wǎng)頁,我們需要對其進行找包,如圖,這個包就是我們所需要的。

接著,我們分析下這個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字段中,我們通過正則表達式來進行提取。

爬蟲代碼

根據(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

由于爬取了圖片,有一些是沒人像,有些是男的...而且是為了找到高顏值小姐姐,如果人工篩選費事費力,這里調(diào)用百度的人臉識別API,進行圖片過濾和顏值打分,選出知乎最美小姐姐。

首先,打開網(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,還算給力。

綜合使用

最后,我們逐一請求我們保存的圖片,過濾掉非人物以及男性圖片,獲取小姐姐圖片的分數(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ù)【知乎小姐姐】,下載完整代碼。

留言打卡:說說自己做的最有趣的爬蟲項目吧。最近開始運營社群,公眾號后臺回復(fù)【打卡】,加入打卡學(xué)習(xí)群,2019年一起搞事情。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容