Python有趣|寻找知乎最美小姐姐

浏览: 1663

作者: 罗罗攀
公众号: 罗罗攀

前言

本月将更新八篇Python有趣系列文章。本系列通过多个有趣案例,讲解Python的玩法,其中包含如下内容,一一推进讲解。

  • 爬虫

  • 数据分析

  • 机器学习

项目背景

最近知乎老是给我推送两个问答,一个是长得好看是种什么体验?(https://www.zhihu.com/question/295119062),另一个是女朋友长得好看是怎样的体验?(https://www.zhihu.com/question/29024583/answer/532321853)所以,本文将讲解如何爬取知乎这两个问题的回答中的图片,并通过百度人脸识别api进行颜值打分,选取出知乎最美小姐姐。整个项目流程如下图所示:

网页分析

首先,我们打开一个话题,通过F12查看,可以看到是一个异步加载的网页,我们需要对其进行找包,如图,这个包就是我们所需要的。

接着,我们分析下这个url,可以发现,除了offset用于分页,questions后面的数字为不同问题的ID。之外,其他url的参数都是固定的,所以我们只需要构造这个url,不断循环请求就好了。

  1. 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字段中,我们通过正则表达式来进行提取。

爬虫代码

根据上面的思路,我们编写爬虫代码:

  1. import requests

  2. from lxml import etree

  3. import json

  4. import time

  5. import re


  6. headers = {

  7. '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',

  8. 'cookie':''

  9. }


  10. def get_img(url):

  11. res = requests.get(url,headers=headers)

  12. i = 1

  13. json_data = json.loads(res.text)

  14. datas = json_data['data']

  15. for data in datas:

  16. id = data['author']['name']

  17. content = data['content']

  18. imgs = re.findall('img src="(.*?)"',content,re.S)

  19. if len(imgs) == 0:

  20. pass

  21. else:

  22. for img in imgs:

  23. if 'jpg' in img:

  24. res_1 = requests.get(img,headers=headers)

  25. fp = open('row_img/' + id + '+' + str(i) + '.jpg','wb')

  26. fp.write(res_1.content)

  27. i = i + 1

  28. print(id,img)


  29. if __name__ == '__main__':

  30. 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)]

  31. for url in urls:

  32. get_img(url)

  33. 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:

  1. import requests


  2. ak = ''

  3. sk = ''


  4. host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(ak,sk)


  5. res = requests.post(host)

  6. print(res.text)

我们拿着token,来请求对应的网页就可以获取图片的内容了。我们拿张超越妹妹的图片做例子~

  1. import base64

  2. import json


  3. token = ''


  4. def get_img_base(file):

  5. with open(file,'rb') as fp:

  6. content = base64.b64encode(fp.read())

  7. return content


  8. request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"

  9. request_url = request_url + "?access_token=" + token


  10. params = {

  11. 'image':get_img_base('test.jpg'),

  12. 'image_type':'BASE64',

  13. 'face_field':'age,beauty,gender'

  14. }


  15. res = requests.post(request_url,data=params)

  16. result = res.text

  17. json_result = json.loads(result)

  18. code = json_result['error_code']

  19. gender = json_result['result']['face_list'][0]['gender']['type']

  20. beauty = json_result['result']['face_list'][0]['beauty']

  21. print(code,gender,beauty)


  22. ### result 0 female 76.25

这里的token为前面请求得到的,params的参数中,图片需要base64编码~超越妹妹76.25,还算给力。

综合使用

最后,我们逐一请求我们保存的图片,过滤掉非人物以及男性图片,获取小姐姐图片的分数(这里处理为1-10分),并分别存在不同的文件夹中。

  1. import requests

  2. import os

  3. import base64

  4. import json

  5. import time


  6. def get_img_base(file):

  7. with open(file,'rb') as fp:

  8. content = base64.b64encode(fp.read())

  9. return content


  10. file_path = 'row_img'

  11. list_paths = os.listdir(file_path)

  12. for list_path in list_paths:

  13. img_path = file_path + '/' + list_path

  14. # print(img_path)


  15. token = '24.a2d7a4d09435e716cf1cb163f176cb12.2592000.1553929524.282335-15648650'


  16. request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"

  17. request_url = request_url + "?access_token=" + token


  18. params = {

  19. 'image':get_img_base(img_path),

  20. 'image_type':'BASE64',

  21. 'face_field':'age,beauty,gender'

  22. }


  23. res = requests.post(request_url,data=params)

  24. json_result = json.loads(res.text)

  25. code = json_result['error_code']

  26. if code == 222202:

  27. continue


  28. try:

  29. gender = json_result['result']['face_list'][0]['gender']['type']

  30. if gender == 'male':

  31. continue

  32. beauty = json_result['result']['face_list'][0]['beauty']

  33. new_beauty = round(beauty/10,1)

  34. print(img_path,new_beauty)

  35. if new_beauty >= 8:

  36. os.rename(os.path.join(file_path,list_path),os.path.join('8分',str(new_beauty) + '+' + list_path))

  37. elif new_beauty >= 7:

  38. os.rename(os.path.join(file_path,list_path),os.path.join('7分',str(new_beauty) + '+' + list_path))

  39. elif new_beauty >= 6:

  40. os.rename(os.path.join(file_path,list_path),os.path.join('6分',str(new_beauty) + '+' + list_path))

  41. elif new_beauty >= 5:

  42. os.rename(os.path.join(file_path,list_path),os.path.join('5分',str(new_beauty) + '+' + list_path))

  43. else:

  44. os.rename(os.path.join(file_path,list_path),os.path.join('其他分',str(new_beauty) + '+' + list_path))

  45. time.sleep(1)


  46. except KeyError:

  47. pass

  48. except TypeError:

  49. pass

代码下载:公众号后台回复【知乎小姐姐】,下载完整代码。

Python的爱好者社区历史文章大合集

2018年Python爱好者社区历史文章合集(作者篇)

2018年Python爱好者社区历史文章合集(类型篇)

福利:文末扫码关注公众号,“Python爱好者社区”,开始学习Python课程:

关注后在公众号内回复“ 课程 ”即可获取:

小编的转行入职数据科学(数据分析挖掘/机器学习方向)【最新免费】

小编的Python的入门免费视频课程

小编的Python的快速上手matplotlib可视化库!

崔老师爬虫实战案例免费学习视频。

陈老师数据分析报告扩展制作免费学习视频。

玩转大数据分析!Spark2.X + Python精华实战课程免费学习视频。

推荐 0
本文由 Python爱好者社区 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册