用 Python 寻找知乎最美小姐姐

百家 作者:程序人生 2019-04-27 04:44:10

最近知乎老是给我推送两个问答,一个是「长得好看是种什么体验?」,另一个是「女朋友长得好看是怎样的体验?」。


所以,本文将讲解如何爬取知乎这两个问题的回答中的图片,并通过百度人脸识别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 requestsfrom lxml import etreeimport jsonimport timeimport 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 = 1json_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:passelse: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 + 1print(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

由于爬取了图片,有一些是没人像,有些是男的...而且是为了找到高颜值小姐姐,如果人工筛选费事费力,这里调用百度的人脸识别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 base64import 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.textjson_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 requestsimport osimport base64import jsonimport 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':continuebeauty = 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:passexcept TypeError:pass


关于作者:罗攀,知名论坛Python爬虫专题管理员。擅长Python爬虫技术,并对Python数据分析与挖掘也有研究。曾经在CSDN等多个知名博客网站发表多篇技术文章(CSDN博客地址:https://blog.csdn.net/luoluopan),深受读者的喜爱。由于热爱爬虫还写了一本《从零开始学Python数据分析》,目前从事线上Python网络爬虫的培训工作。


扫码或者点击封面购买


本书便是一本“小白”学习Python数据分析的入门图书。书中不仅有各种分析框架的使用技巧,而且也有各类数据图表的绘制方法。本书通过多个案例讲解,让读者可以体验数据背后的乐趣。

本书特色:

  • 视频教学,高效、直观

  • 内容全面,讲解系统

  • 给出了数据分析环境的安装和配置步骤

  • 详细介绍了数据分析的流程

  • 提供了9个有较高应用价值的项目案例,有很强的实用性

  • 提供教学PPT,方便教学和学习


扫码购买

关注公众号:拾黑(shiheibook)了解更多

[广告]赞助链接:

四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

公众号 关注网络尖刀微信公众号
随时掌握互联网精彩
赞助链接