python 知乎数据获取

基于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 即可安装。

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

  

from zhihu_oauth import ZhihuClient
from zhihu_oauth.exception import NeedCaptchaException
client = ZhihuClient()
user = 'email_or_phone'
pwd = 'password'
try:
    client.login(user, pwd)
    print(u"登陆成功!")
except NeedCaptchaException: # 处理要验证码的情况
    # 保存验证码并提示输入,重新登录
    with open('a.gif', 'wb') as f:
        f.write(client.get_captcha())
    captcha = input('please input captcha:')
    client.login('email_or_phone', 'password', captcha)

client.save_token('token.pkl') # 保存token
#有了token之后,下次登录就可以直接加载token文件了
# client.load_token('filename')
 

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

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

from __future__ import print_function # 使用python3的print方法
from zhihu_oauth import ZhihuClient

client = ZhihuClient()
client.load_token('token.pkl') # 加载token文件
# 显示自己的相关信息
me = client.me()

# 获取最近 5 个回答
for _, answer in zip(range(5), me.answers):
    print(answer.question.title, answer.voteup_count)

print('----------')

# 获取点赞量最高的 5 个回答
for _, answer in zip(range(5), me.answers.order_by('votenum')):
    print(answer.question.title, answer.voteup_count)

print('----------')

# 获取最近提的 5 个问题
for _, question in zip(range(5), me.questions):
    print(question.title, question.answer_count)

print('----------')

# 获取最近发表的 5 个文章
for _, article in zip(range(5), me.articles):
    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行代码(去掉注释)。分享给大家。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2017/5/3 14:27
# @Author : wang
# @Email  : 540913723@qq.com
# @File   : save_images.py
'''
@Description:保存知乎某个问题下所有答案的图片
'''
from __future__ import print_function # 使用python3的print方法
from zhihu_oauth import ZhihuClient
import re
import os
import urllib

client = ZhihuClient()
# 登录
client.load_token('token.pkl') # 加载token文件
id = 24400664 # https://www.zhihu.com/question/24400664(长得好看是一种怎么样的体验)
question = client.question(id)
print(u"问题:",question.title)
print(u"回答数量:",question.answer_count)
# 建立存放图片的文件夹
os.mkdir(question.title + u"(图片)")
path = question.title + u"(图片)"
index = 1 # 图片序号
for answer in question.answers:
    content = answer.content # 回答内容
    re_compile = re.compile(r'<img src="(https://pic\d\.zhimg\.com/.*?\.(jpg|png))".*?>')
    img_lists = re.findall(re_compile,content)
    if(img_lists):
        for img in img_lists:
            img_url = img[0] # 图片url
            urllib.urlretrieve(img_url,path+u"/%d.jpg" % index)
            print(u"成功保存第%d张图片" % index)
            index += 1

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

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇亲

你的鼓励将我创作最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值