本月将更新八篇Python有趣系列文章。本系列通过多个有趣案例,讲解Python的玩法,其中包含如下内容,一一推进讲解。
最近知乎老是给我推送两个问答,一个是长得好看是种什么体验?,另一个是女朋友长得好看是怎样的体验?所以,本文将讲解如何爬取知乎这两个问题的回答中的图片,并通过百度人脸识别api进行颜值打分,选取出知乎最美小姐姐。整个项目流程如下图所示:
首先,我们打开一个话题,通过F12查看,可以看到是一个异步加载的网页,我们需要对其进行找包,如图,这个包就是我们所需要的。
接着,我们分析下这个url,可以发现,除了offset用于分页,questions后面的数字为不同问题的ID。之外,其他url的参数都是固定的,所以我们只需要构造这个url,不断循环请求就好了。
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
返回的数据为json数据,我们这里只是需要图片,所以只提取用户昵称和内容(昵称用于图片取名,内容中有图片信息)。
图片信息存在content字段中,我们通过正则表达式来进行提取。
根据上面的思路,我们编写爬虫代码:
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需要换成自己的,我们图片的命名为用户昵称+数字(由于一个回答可能有多个图片),结果如图,这样,就解锁了一份小姐姐图片。
由于爬取了图片,有一些是没人像,有些是男的...而且是为了找到高颜值小姐姐,如果人工筛选费事费力,这里调用百度的人脸识别API,进行图片过滤和颜值打分,选出知乎最美小姐姐。
首先,打开网址(http://ai.baidu.com/tech/face),登陆后立即使用,我们首先创建一个人脸识别的应用。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,来请求对应的网页就可以获取图片的内容了。我们拿张超越妹妹的图片做例子~
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的参数中,图片需要base64编码~超越妹妹76.25,还算给力。
最后,我们逐一请求我们保存的图片,过滤掉非人物以及男性图片,获取小姐姐图片的分数(这里处理为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