使用BeautifulSoup模块和urllib2模块实现,然后保存成word是使用python docx模块的,安装方式网上一搜一大堆,我就不再赘述了.
主要实现的功能是登陆知乎,然后将个人收藏的问题和答案获取到之后保存为word文档,以便没有网络的时候可以查阅.当然,答案中如果有图片的话也是可以获取到的.不过这块还是有点问题的.等以后有时间了在修改修改吧.
还有就是正则,用的简直不要太烂…鄙视下自己…
还有,现在是问题的话所有的答案都会保存下来的.看看有时间修改成只保存第一个答案或者收藏页问题的答案吧.要不然如果收藏的太多了的话保存下来的word会吓你一跳的哦.O(∩_∩)O哈哈~
在登陆的时候可能会需要验证码,如果提示输入验证码的话在程序的文件夹下面就可以看到验证码的图片,照着输入就ok了.
# -*- coding: utf-8 -*- #登陆知乎抓取个人收藏 然后保存为word import sys reload(sys) sys.setdefaultencoding('utf-8') import urllib import urllib2 import cookielib import string import re from bs4 import BeautifulSoup from docx import Document from docx import * from docx.shared import Inches from sys import exit import os #这儿是因为在公司上网的话需要使用socket代理 #import socks #import socket #socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,"127.0.0.1",8088) #socket.socket =socks.socksocket loginurl='http://HdhCmsTestzhihu测试数据/login' headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36',} postdata={ '_xsrf': 'acab9d276ea217226d9cc94a84a231f7', 'email': '', 'password': '', 'rememberme':'y' } if not os.path.exists('myimg'): os.mkdir('myimg') if os.path.exists('123.docx'): os.remove('123.docx') if os.path.exists('checkcode.gif'): os.remove('checkcode.gif') mydoc=Document() questiontitle='' #---------------------------------------------------------------------- def dealimg(imgcontent): soup=BeautifulSoup(imgcontent) try: for imglink in soup.findAll('img'): if imglink is not None : myimg= imglink.get('src') #print myimg if myimg.find('http')>=0: imgsrc=urllib2.urlopen(myimg).read() imgnamere=re测试数据pile(r'http\S*/') imgname=imgnamere.sub('',myimg) #print imgname with open(u'myimg'+'/'+imgname,'wb') as code: code.write(imgsrc) mydoc.add_picture(u'myimg/'+imgname,width=Inches(1.25)) except: pass strinfo=re测试数据pile(r' [\s\S]* ') imgcontent=strinfo.sub('',imgcontent) strinfo=re测试数据pile(r' ') imgcontent=strinfo.sub('',imgcontent) #show all strinfo=re测试数据pile(r'') imgcontent=strinfo.sub('',imgcontent) strinfo=re测试数据pile(r'') imgcontent=strinfo.sub('',imgcontent) imgcontent=imgcontent.replace(' ','') imgcontent=imgcontent.replace(' ','').replace('','').replace('','').replace('
','').replace('
','') return imgcontent def enterquestionpage(pageurl): html=urllib2.urlopen(pageurl).read() soup=BeautifulSoup(html) questiontitle=soup.title.string mydoc.add_heading(questiontitle,level=3) for div in soup.findAll('div',{'class':'fixed-summary zm-editable-content clearfix'}): #print div conent=str(div).replace('','').replace('
查看更多关于python实现登陆知乎获得个人收藏并保存为word文件的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did88170