知乎大神用Python爬取高顏值美女(爬蟲+人臉檢測+顏值檢測)

知乎大神用Python爬取高顏值美女(爬蟲+人臉檢測+顏值檢測)

1 數據源

知乎話題『美女』下所有問題中回答所出現的圖片

2 抓取工具

Python 3,並使用第三方庫 Requests、lxml、AipFace,代碼共 100 + 行

3 必要環境

  • Mac / Linux / Windows (Linux 沒測過,理論上可以。Windows 之前較多反應出現異常,後查是 windows 對本地文件名中的字符做了限制,已使用正則過濾)
  • 無需登錄知乎(即無需提供知乎帳號密碼)
  • 人臉檢測服務需要一個百度雲帳號(即百度網盤 / 貼吧帳號)

4 人臉檢測庫

AipFace,由百度雲 AI 開放平臺提供,是一個可以進行人臉檢測的 Python SDK。可以直接通過 HTTP 訪問,免費使用。

5 檢測過濾條件

  • 過濾所有未出現人臉圖片(比如風景圖、未露臉身材照等)
  • 過濾所有非女性(在抓取中,發現知乎男性圖片基本是明星,故不考慮;存在 AipFace 性別識別不準的情況)
  • 過濾所有非真實人物,比如動漫人物 (AipFace Human 置信度小於 0.6)
  • 過濾所有顏值評分較低圖片(AipFace beauty 屬性小於 45,為了節省存儲空間;再次聲明,AipFace 評分無任何客觀性)

6 實現邏輯

  • 通過 Requests 發起 HTTP 請求,獲取『美女』下的部分討論列表
  • 通過 lxml 解析抓取到的每個討論中 HTML,獲取其中所有的 img 標籤相應的 src 屬性
  • 通過 Requests 發起 HTTP 請求,下載 src 屬性指向圖片(不考慮動圖)
  • 通過 AipFace 請求對圖片進行人臉檢測
  • 判斷是否檢測到人臉,並使用 『4 檢測過濾條件』過濾
  • 將過濾後的圖片持久化到本地文件系統,文件名為 顏值 + 作者 + 問題名 + 序號
  • 返回第一步,繼續

7 抓取結果

直接存放在文件夾中(angelababy 實力出境)。另外說句,目前抓下來的圖片,除 baby 外,88 分是最高分。個人對其中的排序表示反對,老婆竟然不是最高分

知乎大神用Python爬取高顏值美女(爬蟲+人臉檢測+顏值檢測)

知乎大神用Python爬取高顏值美女(爬蟲+人臉檢測+顏值檢測)

知乎大神用Python爬取高顏值美女(爬蟲+人臉檢測+顏值檢測)

代碼

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
#這是話題『美女』的 ID,其是『顏值』(20013528)的父話題
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
#某話題下討論列表請求 url
BASE_URL = "https://www.zhihu.com/api/v4/topics/%s/feeds/timeline_activity"
#初始請求 url 附帶的請求參數
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)
#指定 url,獲取對應原始內容 / 圖片
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
#指定 url,獲取對應 JSON 返回 / 話題列表
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:
continue
#解析列表中每一個元素的內容
html = etree.HTML(target["content"])
seq = 0

#question_url = target["question"]["url"]
question_title = target["question"]["title"]
author_name = target["author"]["name"]
#author_id = target["author"]["url_token"]
print("current answer: " + question_title + " author: " + author_name)
#獲取所有圖片地址
images = html.xpath("//img/@src")
for image in images:
if not image.startswith("http"):
continue
s = 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)
#注意文件名的處理,不同平臺的非法字符不一樣,這裡只做了簡單處理,特別是 author_name / question_title 中的內容
seq = seq + 1
with open(os.path.join(DIR, filename), "wb") as fd:
fd.write(s)
#人臉檢測 免費,但有 QPS 限制
time.sleep(2)
if not datums["paging"]["is_end"]:
#獲取後續討論列表的請求 url
return datums["paging"]["next"]
else:
return None
def get_valid_filename(s):
s = str(s).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\\w.]', '_', s)
def init_face_detective(app_id, api_key, secret_key):
client = AipFace(app_id, api_key, secret_key)
#人臉檢測中,在響應中附帶額外的字段。年齡 / 性別 / 顏值 / 質量
options = {"face_fields": "age,gender,beauty,qualities"}
def detective(image):
r = client.detect(image, options)
#如果沒有檢測到人臉
if r["result_num"] == 0:
return []

scores = []
for face in r["result"]:
#人臉置信度太低
if face["face_probability"] < 0.6:
continue
#真實人臉置信度太低
if face["qualities"]["type"]["human"] < 0.6:
continue
#顏值低於閾值
if face["beauty"] < BEAUTY_THRESHOLD:
continue
#性別非女性
if face["gender"] != "female":
continue
scores.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)
# vim: set ts=4 sw=4 sts=4 tw=100 et:

9 運行準備

  • 安裝 Python 3,Download Python
  • 安裝 requests、lxml、baidu-aip 庫,都可以通過 pip 安裝,一行命令
  • 申請百度雲檢測服務,免費。人臉識別-百度AI
"


分享到:


相關文章: