生活随笔
收集整理的這篇文章主要介紹了
Python 爬虫 + 人脸检测 —— 知乎高颜值图片抓取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 數據源
知乎 話題『美女』下所有問題中回答所出現的圖片
2 抓取工具
Python 3,并使用第三方庫 Requests、lxml、AipFace,代碼共 100 + 行
3 必要環境
Mac / Linux / Windows (Linux 沒測過,理論上可以。Windows 之前較多反應出現異常,后查是 windows 對本地文件名中的字符做了限制,已使用正則過濾),無需登錄知乎(即無需提供知乎帳號密碼),人臉檢測服務需要一個百度云帳號(即百度網盤 / 貼吧帳號)
4 人臉檢測庫
AipFace,由百度云 AI 開放平臺提供,是一個可以進行人臉檢測的 Python SDK??梢灾苯油ㄟ^ HTTP 訪問,免費使用
http://ai.baidu.com/ai-doc/FACE/fk3co86lr
5 檢測過濾條件
- 過濾所有未出現人臉圖片(比如風景圖、未露臉身材照等)
- 過濾所有非女性(在抓取中,發現知乎男性圖片基本是明星,故不考慮;存在 AipFace 性別識別不準的情況)
- 過濾所有非真實人物,比如動漫人物 (AipFace Human 置信度小于 0.6)
- 過濾所有顏值評分較低圖片(AipFace beauty 屬性小于 45,為了節省存儲空間;再次聲明,AipFace 評分無任何客觀性)
在這里還是要推薦下我自己建的Python開發學習群:810735403
6 實現邏輯
- 通過 Requests 發起 HTTP 請求,獲取『美女』下的部分討論列表
- 通過 lxml 解析抓取到的每個討論中 HTML,獲取其中所有的 img 標簽相應的 src 屬性
- 通過 Requests 發起 HTTP 請求,下載 src 屬性指向圖片(不考慮動圖)
- 通過 AipFace 請求對圖片進行人臉檢測
- 判斷是否檢測到人臉,并使用 『4 檢測過濾條件』過濾
- 將過濾后的圖片持久化到本地文件系統,文件名為 顏值 + 作者 + 問題名 + 序號
- 返回第一步,繼續
7 抓取結果
直接存放在文件夾中(angelababy 實力出境)。另外說句,目前抓下來的圖片,除 baby 外,88 分是最高分。個人對其中的排序表示反對,老婆竟然不是最高分
8 代碼
- 8.1 直接使用 百度云 Python-SDK 代碼 —— 已移除
- 8.2不使用 SDK,直接構造 HTTP 請求版本。直接使用這個版本有個好處,就是不依賴于 SDK 的版本(百度云現在有兩個版本的接口 —— V2 和 V3?,F階段,百度云同時支持兩種接口,所以直接使用 SDK 是沒問題的。等以后哪一天百度不支持 V2 了,就務必升級
SDK 或使用這個直接構造 HTTP 版本)
import time
import os
import re
import requests
from lxml
import etree
from aip
import AipFace
APP_ID
= "xxxxxxxx"
API_KEY
= "xxxxxxxxxxxxxxxxxxxxxxxx"
SECRET_KEY
= "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
DIR
= "image"
BEAUTY_THRESHOLD
= 45
AUTHORIZATION
= "oauth c3cef7c66a1843f8b3a9e6a1e3160e20"
LIMIT
= 5
SOURCE
= "19552207"
USER_AGENT
= "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.5 Safari/534.55.3"
REFERER
= "https://www.zhihu.com/topic/%s/newest" % SOURCE
BASE_URL
= "https://www.zhihu.com/api/v4/topics/%s/feeds/timeline_activity"
URL_QUERY
= "?include=data%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Danswer%29%5D.target.content%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%3Bdata%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Danswer%29%5D.target.is_normal%2Ccomment_count%2Cvoteup_count%2Ccontent%2Crelevant_info%2Cexcerpt.author.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Darticle%29%5D.target.content%2Cvoteup_count%2Ccomment_count%2Cvoting%2Cauthor.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Dtopic_sticky_module%29%5D.target.data%5B%3F%28target.type%3Dpeople%29%5D.target.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Danswer%29%5D.target.content%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%3Bdata%5B%3F%28target.type%3Danswer%29%5D.target.author.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Darticle%29%5D.target.content%2Cauthor.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics%3Bdata%5B%3F%28target.type%3Dquestion%29%5D.target.comment_count&limit=" + str(LIMIT
)
def fetch_image(url
):try:headers
= {"User-Agent": USER_AGENT
,"Referer": REFERER
,"authorization": AUTHORIZATION
}s
= requests
.get
(url
, headers
=headers
)except Exception
as e
:print("fetch last activities fail. " + url
)raise e
return s
.content
def fetch_activities(url
):try:headers
= {"User-Agent": USER_AGENT
,"Referer": REFERER
,"authorization": AUTHORIZATION
}s
= requests
.get
(url
, headers
=headers
)except Exception
as e
:print("fetch last activities fail. " + url
)raise e
return s
.json
()
def process_activities(datums
, face_detective
):for data
in datums
["data"]:target
= data
["target"]if "content" not in target
or "question" not in target
or "author" not in target
:continuehtml
= etree
.HTML
(target
["content"])seq
= 0question_title
= target
["question"]["title"]author_name
= target
["author"]["name"]print("current answer: " + question_title
+ " author: " + author_name
)images
= html
.xpath
("//img/@src")for image
in images
:if not image
.startswith
("http"):continues
= fetch_image
(image
)scores
= face_detective
(s
)for score
in scores
:filename
= ("%d--" % score
) + author_name
+ "--" + question_title
+ ("--%d" % seq
) + ".jpg"filename
= re
.sub
(r
'(?u)[^-\w.]', '_', filename
)seq
= seq
+ 1with open(os
.path
.join
(DIR
, filename
), "wb") as fd
:fd
.write
(s
)time
.sleep
(2)if not datums
["paging"]["is_end"]:return datums
["paging"]["next"]else:return Nonedef get_valid_filename(s
):s
= str(s
).strip
().replace
(' ', '_')return re
.sub
(r
'(?u)[^-\w.]', '_', s
)import base64
def detect_face(image
, token
):try:URL
= "https://aip.baidubce.com/rest/2.0/face/v3/detect"params
= {"access_token": token
}data
= {"face_field": "age,gender,beauty,qualities","image_type": "BASE64","image": base64
.b64encode
(image
)}s
= requests
.post
(URL
, params
=params
, data
=data
)return s
.json
()["result"]except Exception
as e
:print("detect face fail. " + url
)raise e
def fetch_auth_token(api_key
, secret_key
):try:URL
= "https://aip.baidubce.com/oauth/2.0/token"params
= {"grant_type": "client_credentials","client_id": api_key
,"client_secret": secret_key
}s
= requests
.post
(URL
, params
=params
)return s
.json
()["access_token"]except Exception
as e
:print("fetch baidu auth token fail. " + url
)raise e
def init_face_detective(app_id
, api_key
, secret_key
):token
= fetch_auth_token
(api_key
, secret_key
)def detective(image
):r
= detect_face
(image
, token
)if r
is None or r
["face_num"] == 0:return []scores
= []for face
in r
["face_list"]:if face
["face_probability"] < 0.6:continueif face
["beauty"] < BEAUTY_THRESHOLD
:continueif face
["gender"]["type"] != "female":continuescores
.append
(face
["beauty"])return scores
return detective
def init_env():if not os
.path
.exists
(DIR
):os
.makedirs
(DIR
)init_env
()
face_detective
= init_face_detective
(APP_ID
, API_KEY
, SECRET_KEY
)url
= BASE_URL
% SOURCE
+ URL_QUERY
while url
is not None:print("current url: " + url
)datums
= fetch_activities
(url
)url
= process_activities
(datums
, face_detective
)time
.sleep
(5)
9 運行準備
- 安裝 Python 3,Download Python
- 安裝 requests、lxml、baidu-aip 庫,都可以通過 pip 安裝,一行命令
- 申請百度云檢測服務,免費。人臉識別-百度AI
將 AppID ApiKek SecretKey 填寫到 代碼 中 - (可選)配置自定義信息,如圖片存儲目錄、顏值閾值、人臉置信度等
- (可選)若請求知乎失敗,返回如下。需填寫
AUTHORIZATION,可從開發者工具中獲取(如下圖,換了幾個瀏覽器,目前沒登錄情況該值都是一樣的。知乎對爬蟲的態度比較開放,不知道后續是否會更換)
{"error": {"message": "ZERR_NO_AUTH_TOKEN","code": 100,"name": "AuthenticationInvalidRequest"}
}
Chrome 瀏覽器;找一個知乎鏈接點進去,打開開發者工具,查看 HTTP 請求 header;無需登錄
- 運行
^*^
10 結語
因是人臉檢測,所以可能有些福利會被篩掉。百度圖像識別 API 還有一個叫做色情識別。這個 API 可以識別不可描述以及性感指數程度,可以用這個 API 來找福利
https://cloud.baidu.com/product/imagecensoring
- 如果實在不想申請百度云服務,可以直接把人臉檢測部分注釋掉,當做單純的爬蟲使用
- 人臉檢測部分可以替換成其他廠商服務或者本地模型,這里用百度云是因為它不要錢
- 抓了幾千張照片,效果還是挺不錯的。有興趣可以把代碼貼下來跑跑試試
- 這邊文章只是基礎爬蟲 + 數據過濾來獲取較高質量數據的示例,希望有興趣者可以 run
下,代碼里有很多地方可以很容易的修改,從最簡單的數據源話題變更、抓取數據字段增加和刪除到圖片過濾條件修改都很容易。如果再稍微花費時間,變更為抓取某人動態(比如輪子哥,數據質量很高)、探索
HTTP 請求中哪些 header 和 query
是必要的,文中代碼都只需要非常局部性的修改。至于人臉探測,或者其他機器學習接口,可以提供非常多的功能用于數據過濾,但哪些過濾是具備高可靠性,可信賴的且具備可用性,這個大概是經驗和反復試驗,這就是額外的話題了;順便希望大家有良好的編碼習慣 - 最后再次聲明,顏值得分以及性別過濾存在 bad case,請勿認真對待
在這里還是要推薦下我自己建的Python開發學習群:810735403,群里都是學Python開發的,如果你正在學習Python ,歡迎你加入,大家都是軟件開發黨,不定期分享干貨(只有Python軟件開發相關的),包括我自己整理的一份2020最新的Python進階資料和高級開發教程,歡迎進階中和進想深入Python的小伙伴!
**以下內容無用,為本篇博客被搜索引擎抓取使用
(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)
python 是干什么的 零基礎學 python 要多久 python 為什么叫爬蟲
python 爬蟲菜鳥教程 python 爬蟲萬能代碼 python 爬蟲怎么掙錢
python 基礎教程 網絡爬蟲 python python 爬蟲經典例子
python 爬蟲
(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)( ̄︶ ̄)( ̄︶ ̄)
以上內容無用,為本篇博客被搜索引擎抓取使用
總結
以上是生活随笔為你收集整理的Python 爬虫 + 人脸检测 —— 知乎高颜值图片抓取的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。