基于python的知乎开源爬虫 zhihu_oauth使用介绍

  今天在无意之中发现了一个知乎的开源爬虫,是基于Python的,名字叫zhihu_oauth,看了一下在github上面star数还挺多的,貌似文档也挺详细的,于是就稍微研究了一下。发现果然很好用啊。就在这里给大家介绍一下如何使用。

  项目的主页地址在:https://github.com/7sDream/zhihu-oauth。作者的知乎主页为:https://www.zhihu.com/people/7sdream/。

  项目的文档地址为:http://zhihu-oauth.readthedocs.io/zh_CN/latest/index.html 。讲道理,原作者对于该怎么使用这个库已经讲的非常详细了,我在这里再重复一遍简直就是画蛇添足。所以大家要是想详细了解这个库怎么用,就去官方文档吧。我只说一下我觉得需要补充的重要的几点。

  首先是安装。作者已经将项目上传到pypi了,所以我们可以直接使用pip进行安装了。按照作者的说法,项目对于Python3的支持更好,淡然目前也是兼容Python2的,所以大家最好使用python3.直接 pip3 install -U zhihu_oauth 即可安装。

  安装好了第一步就是登陆。直接使用下面的代码就可以登陆。

  

 1 from zhihu_oauth import ZhihuClient
 2 from zhihu_oauth.exception import NeedCaptchaException
 3 client = ZhihuClient()
 4 user = 'email_or_phone'
 5 pwd = 'password'
 6 try:
 7     client.login(user, pwd)
 8     print(u"登陆成功!")
 9 except NeedCaptchaException: # 处理要验证码的情况
10     # 保存验证码并提示输入,重新登录
11     with open('a.gif', 'wb') as f:
12         f.write(client.get_captcha())
13     captcha = input('please input captcha:')
14     client.login('email_or_phone', 'password', captcha)
15 
16 client.save_token('token.pkl') # 保存token
17 #有了token之后,下次登录就可以直接加载token文件了
18 # client.load_token('filename')

上面的代码是直接使用账号密码登陆,最后保存了登陆之后的token,在下次登录的时候我们就可以直接使用token登录而不用每次都输入密码了。

在登录完成之后,可以干的事情当然就很多了,比如下面的代码就可以获得自己的知乎账户的基本信息

 1 from __future__ import print_function # 使用python3的print方法
 2 from zhihu_oauth import ZhihuClient
 3 
 4 client = ZhihuClient()
 5 client.load_token('token.pkl') # 加载token文件
 6 # 显示自己的相关信息
 7 me = client.me()
 8 
 9 # 获取最近 5 个回答
10 for _, answer in zip(range(5), me.answers):
11     print(answer.question.title, answer.voteup_count)
12 
13 print('----------')
14 
15 # 获取点赞量最高的 5 个回答
16 for _, answer in zip(range(5), me.answers.order_by('votenum')):
17     print(answer.question.title, answer.voteup_count)
18 
19 print('----------')
20 
21 # 获取最近提的 5 个问题
22 for _, question in zip(range(5), me.questions):
23     print(question.title, question.answer_count)
24 
25 print('----------')
26 
27 # 获取最近发表的 5 个文章
28 for _, article in zip(range(5), me.articles):
29     print(article.title, article.voteup_count)

当然可以干的事情还远远不止这些,比如我们知道了某个问题的url地址或者问题id,就可以获得这个问题下有多少个回答,作者的信息等等一系列详细的信息。开发者想的真的挺周到的,一般常见的需要的信息基本全部都包括了。具体的代码我就不贴了,大家自行参考官方文档。

一个小的tips:由于这个库有好多个类,比如获得作者信息的类,获得文章信息的类等等。每个类都有非常多的方法,我去看了一下官方文档,作者有些类的属性就没有完全列出来,那么我们怎么查看这个类全部的属性呢?其实很简单,只需要使用python的dir函数就可以了,使用dir(object)可以查看object类(或对象)的全部属性。比如我们有一个answer类对象,使用dir(answer)就会返回answer对象所有属性的列表。除去默认的一些属性之外,我们就可以找到这个类的我们需要的属性了,很方便吧。(下面是collection即收藏夹类的全部属性)

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_build_data', '_build_params', '_build_url', '_cache', '_data', '_get_data', '_id', '_method', '_refresh_times', '_session', 'answer_count', 'answers', 'articles', 'comment_count', 'comments', 'contents', 'created_time', 'creator', 'description', 'follower_count', 'followers', 'id', 'is_public', 'pure_data', 'refresh', 'title', 'updated_time']

最后,我使用这个类,抓取了知乎某个问题下所有回答中的图片(抓美女图,哈哈哈哈),只用了不到30行代码(去掉注释)。分享给大家。

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time   : 2017/5/3 14:27
 4 # @Author : Lyrichu
 5 # @Email  : 919987476@qq.com
 6 # @File   : save_images.py
 7 '''
 8 @Description:保存知乎某个问题下所有答案的图片
 9 '''
10 from __future__ import print_function # 使用python3的print方法
11 from zhihu_oauth import ZhihuClient
12 import re
13 import os
14 import urllib
15 
16 client = ZhihuClient()
17 # 登录
18 client.load_token('token.pkl') # 加载token文件
19 id = 24400664 # https://www.zhihu.com/question/24400664(长得好看是一种怎么样的体验)
20 question = client.question(id)
21 print(u"问题:",question.title)
22 print(u"回答数量:",question.answer_count)
23 # 建立存放图片的文件夹
24 os.mkdir(question.title + u"(图片)")
25 path = question.title + u"(图片)"
26 index = 1 # 图片序号
27 for answer in question.answers:
28     content = answer.content # 回答内容
29     re_compile = re.compile(r'<img src="(https://pic\d\.zhimg\.com/.*?\.(jpg|png))".*?>')
30     img_lists = re.findall(re_compile,content)
31     if(img_lists):
32         for img in img_lists:
33             img_url = img[0] # 图片url
34             urllib.urlretrieve(img_url,path+u"/%d.jpg" % index)
35             print(u"成功保存第%d张图片" % index)
36             index += 1

如果要是自己写的话,直接抓取解析网页是无法获得全部回答的,所以只能去破解知乎的api,比较麻烦,使用这个现成的轮子就方便很多了。以后想慢慢欣赏知乎的美女就再也不用发愁啦,嘿嘿嘿。

posted @ 2017-05-03 15:44  lyrichu  阅读(4869)  评论(1编辑  收藏  举报