下载知乎指定问题的答案并保存图片

代码如下:

 
  
from zhihu_oauth import ZhihuClient

from zhihu_oauth.exception import NeedCaptchaException
from docx import Document
from docx.shared import Inches
from w3lib.html import remove_tags
import urllib.request
from io import StringIO
import subprocess
import re
document = Document()
client = ZhihuClient()


try
: client.login('username', 'pass') except NeedCaptchaException: # 保存验证码并提示输入,重新登录 with open('a.gif', 'wb') as f: f.write(client.get_captcha()) captcha = input('please input captcha:') client.login('898311543@qq.com', '1818039565', captcha) p = re.compile('<img.*>') num = input('请输入问题序号:') question = client.question(int(num)) i = 0; file = open(question.title+'.html','w') file.write('<html><head></head><body>') # document.add_heading(question.title, 0) file.write('<h1>'+question.title+'</h1>') for answer in question.answers: # print(question.answers[0].content.replace('<br>','\n')) # print(question.answers[0].voteup_count) print(answer.author.name) # document.add_paragraph("回答者:"+answer.author.name+'\t'+'赞数:'+str(answer.voteup_count), style='IntenseQuote') # document.add_paragraph(remove_tags(answer.content, keep=('img',))) # document.add_page_break() file.write('<br><br>'+"回答者:"+answer.author.name+'&nbsp;&nbsp;'+'赞数:'+str(answer.voteup_count)) file.write('<p>'+answer.content+'</p>') i=i+1 if(i>50): break #document.save(str(question.title)+'.docx') file.write('</body></html>') file.close() subprocess.call(['pandoc',question.title+'.html','-o',question.title+'.docx']) subprocess.call(['rm','-rf',question.title+'.html'])

参考资料:https://github.com/7sDream/zhihu-oauth

这段代码主要利用zhihu-oauth实现对知乎内容的获取,这个项目很好的对知乎的API进行了封装并且非常容易的实现知乎的各种操作。

在Ubuntu系统下通过

pip install -U zhihu_oauth

可以安装zhihu_oauth模块。为以后下载做好准备。

 

在下载知乎文章中主要遇到的问题是,不好处理图片。

当直接将content保存到docx中的时候,会直接将<img>标签保存到docx中,不好处理。后来在issue中找到了比较好的解决方案。

一种解决方案是直接保存成html然后用pandoc转码。具体的代码实现可以参考上面的代码。

 

转载于:https://www.cnblogs.com/shubin/p/7511737.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值