前言
隨着現在直播的興起,主播這個職業逐漸走入人們的視野。現在各大平臺都有當家花旦、一哥、一姐等稱號。其實人氣是一方面,但是顏值纔是硬實力。
接下來帶大家進行主播的顏值檢測評分,看看誰是最靚的崽(*^▽^*)
本篇大致內容:
1、爬取主播的直播人臉圖
2、調用百度人臉檢測開放接口,進行顏值打分
環境介紹:
python 3.6
pycharm
requests
parsel(xapth)
1、爬取主播的圖片
1.1 導入模塊
import requests
import parsel
1.2 分析目標網頁,確定爬取的url路徑,headers參數
代碼如下:
base_url = 'https://www.huya.com/g/4079'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36'}
1.3 發送請求 -- requests 模擬瀏覽器發送請求,獲取響應數據
代碼如下:
response = requests.get(url=base_url, headers=headers)
html_data = response.text
1.4 解析數據 -- parsel 轉化爲Selector對象,Selector對象具有xpath的方法,能夠對轉化的數據進行處理
代碼如下:
parse = parsel.Selector(html_data)
data_list = parse.xpath('//li[@class="game-live-item"]')
# print(data_list)
for data in data_list:
img_url = data.xpath('./a/img/@data-original').get() # 主播人臉圖片的url地址
img_title = data.xpath('.//span/i/@title').get() # 主播的名字
print(img_url, img_title)
# 請求圖片數據
img_data = requests.get(url=img_url, headers=headers).content
1.5 保存數據
代碼如下:
# 準備文件名
file_name = img_title + '.jpg'
with open('img\\' + file_name, mode='wb') as f:
print('正在保存:', file_name)
f.write(img_data)
2、調用百度人臉檢測開放接口
在百度AI開放平臺註冊賬號
點擊進入人臉識別
創建一個應用
創建完成以後進入管理應用,打開應用,點擊下載SDK
不要下載,點擊使用說明
安裝SDK
pip install baidu-aip
根據百度接口示例來寫代碼
代碼如下:
from aip import AipFace
import base64
def face_rg(file_Path):
""" 你的 api_id AK SK """
api_id = '20107883'
api_key = 'Xela0yPoFtERUBSTFtNlEKbO'
secret_key = 'E5TmneyfAzxfzowgwRErLT8RYe7MfkfG'
client = AipFace(api_id, api_key, secret_key) # 調用顏值檢測的接口
with open(file_Path, 'rb') as file:
data = base64.b64encode(file.read()) # 圖片類型 BASE64:圖片的base64值,base64編碼後的圖片數據
image = data.decode()
imageType = "BASE64"
options = {}
options["face_field"] = 'beauty'
""" 調用人臉檢測 """
result = client.detect(image, imageType, options)
print(result)
return result['result']['face_list'][0]['beauty']
if __name__ == '__main__':
face_rg(r'..\主播顏值檢測\img\藍雲-夏花依舊.jpg')
3、檢測打分
3.1 導入模塊,做循環檢測的接口
代碼如下:
import os
from 主播顏值檢測.顏值檢測_接口 import face_rg
path = './img'
image_list = os.listdir(path)
# print(image_list)
score_dict = {}
for image in image_list:
try:
name = image.split('.')[0]
# print(name)
image_path = path + '\\' + image # 圖片的路徑
face_score = face_rg(image_path)
# print(face_score)
score_dict[name] = face_score
# print(score_dict)
except Exception as e:
print('正在檢測:{}|檢測失敗!!!'.format(str(name)))
else:
print('正在檢測:{}|顏值打分爲:{}'.format(str(name), str(face_score)))
print('\n===========================================檢測完成===========================================')
print(score_dict.items())
# 字典根據值降序排列
change_score = sorted(score_dict.items(), key=lambda x: x[1], reverse=True) # lambda中的1是元組的索引
print(change_score)
3.2 數據輸出
for a, b in enumerate(change_score):
print('小姐姐的名字是:{}丨顏值名次是:第{}名丨她的顏值分數爲:{}'.format(change_score[a][0], a+1, change_score[a][1]))
運行代碼後得出最後的顏值打分檢測結果
歡迎點擊右上角關注小編,除了分享技術文章之外還有很多福利,私信學習資料可以領取包括不限於Python實戰演練、PDF電子文檔、面試集錦、學習資料等。