首页 后端开发 Python教程 python实现登陆知乎获得个人收藏并保存为word文件

python实现登陆知乎获得个人收藏并保存为word文件

Jun 10, 2016 pm 03:17 PM
python word 保持 登陆 知乎 获得

这个程序其实很早之前就完成了,一直没有发出了,趁着最近不是很忙就分享给大家.
使用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://www.zhihu.com/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.compile(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.compile(r'<noscript>[\s\S]*</noscript>')
  imgcontent=strinfo.sub('',imgcontent)
  strinfo=re.compile(r'<img  class[\s\S]*</ alt="python实现登陆知乎获得个人收藏并保存为word文件" >')
  imgcontent=strinfo.sub('',imgcontent)
  #show all
  strinfo=re.compile(r'<a class="toggle-expand[\s\S]*</a>')
  imgcontent=strinfo.sub('',imgcontent)
 
  strinfo=re.compile(r'<a class=" wrap external"[\s\S]*rel="nofollow noreferrer" target="_blank">')
  imgcontent=strinfo.sub('',imgcontent)
  imgcontent=imgcontent.replace('<i class="icon-external"></i></a>','')
 
 
  imgcontent=imgcontent.replace('</b>','').replace('</p>','').replace('<p>','').replace('<p>','').replace('<br>','')
  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('<div class="fixed-summary zm-editable-content clearfix">','').replace('</div>','')
     
    conent=conent.decode('utf-8')
    conent=conent.replace('<br/>','\n')
     
    conent=dealimg(conent)
    ###这一块弄得太复杂了 有时间找找看有没有处理html的模块
    conent=conent.replace('<div class="fixed-summary-mask">','').replace('<blockquote>','').replace('<b>','').replace('<strong>','').replace('</strong>','').replace('<em>','').replace('</em>','').replace('</blockquote>','')
    mydoc.add_paragraph(conent,style='BodyText3')
    """file=open('222.txt','a')
    file.write(str(conent))
    file.close()"""
     
 
def entercollectpage(pageurl):
  html=urllib2.urlopen(pageurl).read()
  soup=BeautifulSoup(html)
  for div in soup.findAll('div',{'class':'zm-item'}):
    h2content=div.find('h2',{'class':'zm-item-title'})
    #print h2content
    if h2content is not None:
      link=h2content.find('a')
      mylink=link.get('href')
      quectionlink='http://www.zhihu.com'+mylink
      enterquestionpage(quectionlink)
      print quectionlink    
 
 
 
def loginzhihu():
  postdatastr=urllib.urlencode(postdata)
  '''
  cj = cookielib.LWPCookieJar()
  cookie_support = urllib2.HTTPCookieProcessor(cj)
  opener = urllib2.build_opener(cookie_support,urllib2.HTTPHandler)
  urllib2.install_opener(opener)
  '''
  h = urllib2.urlopen(loginurl)
  request = urllib2.Request(loginurl,postdatastr,headers)
  request.get_origin_req_host
  response = urllib2.urlopen(request)
  #print response.geturl()
  text = response.read()
 
 
  collecturl='http://www.zhihu.com/collections'
  req=urllib2.urlopen(collecturl)
  if str(req.geturl())=='http://www.zhihu.com/&#63;next=%2Fcollections':
    print 'login fail!'
    return
  txt=req.read()
 
  soup=BeautifulSoup(txt)
  count=0
  divs =soup.findAll('div',{'class':'zm-item'})
  if divs is None:
    print 'login fail!'
    return
  print 'login ok!\n'
  for div in divs:
     
    link=div.find('a')
    mylink=link.get('href')
    collectlink='http://www.zhihu.com'+mylink
    entercollectpage(collectlink)
    print collectlink
    #这儿是当时做测试用的,值获取一个收藏
    #count+=1
    #if count==1:
    #  return
     
 
def getcheckcode(thehtml):
  soup=BeautifulSoup(thehtml)
  div=soup.find('div',{'class':'js-captcha captcha-wrap'})
  if div is not None:
    #print div
    imgsrc=div.find('img')
    imglink=imgsrc.get('src')
    if imglink is not None:
      imglink='http://www.zhihu.com'+imglink
 
      imgcontent=urllib2.urlopen(imglink).read()
      with open('checkcode.gif','wb') as code:
        code.write(imgcontent)
      return True
    else:
      return False
  return False
 
 
if __name__=='__main__':
   
  import getpass
  username=raw_input('input username:')
  password=getpass.getpass('Enter password: ') 
   
  postdata['email']=username
  postdata['password']=password
  postdatastr=urllib.urlencode(postdata)
  cj = cookielib.LWPCookieJar()
  cookie_support = urllib2.HTTPCookieProcessor(cj)
  opener = urllib2.build_opener(cookie_support,urllib2.HTTPHandler)
  urllib2.install_opener(opener)
 
  h = urllib2.urlopen(loginurl)
  request = urllib2.Request(loginurl,postdatastr,headers)
  response = urllib2.urlopen(request)
  txt = response.read()
 
  if getcheckcode(txt):
    checkcode=raw_input('input checkcode:')
    postdata['captcha']=checkcode
    loginzhihu()
    mydoc.save('123.docx')
  else:
    loginzhihu()
    mydoc.save('123.docx')
 
  print 'the end'
  raw_input()
登录后复制

好了,大概就是这样,大家如果有什么好的建议或者什么的可以再下面留言,我会尽快回复的.或者在小站的关于页面有我的联系方式,直接联系我就ok.

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

C语言 sum 的作用是什么? C语言 sum 的作用是什么? Apr 03, 2025 pm 02:21 PM

C语言中没有内置求和函数,需自行编写。可通过遍历数组并累加元素实现求和:循环版本:使用for循环和数组长度计算求和。指针版本:使用指针指向数组元素,通过自增指针遍历高效求和。动态分配数组版本:动态分配数组并自行管理内存,确保释放已分配内存以防止内存泄漏。

distinctIdistinguish有关系吗 distinctIdistinguish有关系吗 Apr 03, 2025 pm 10:30 PM

distinct 和 distinguish 虽都与区分有关,但用法不同:distinct(形容词)描述事物本身的独特性,用于强调事物之间的差异;distinguish(动词)表示区分行为或能力,用于描述辨别过程。在编程中,distinct 常用于表示集合中元素的唯一性,如去重操作;distinguish 则体现在算法或函数的设计中,如区分奇数和偶数。优化时,distinct 操作应选择合适的算法和数据结构,而 distinguish 操作应优化区分逻辑效率,并注意编写清晰可读的代码。

谁得到更多的Python或JavaScript? 谁得到更多的Python或JavaScript? Apr 04, 2025 am 12:09 AM

Python和JavaScript开发者的薪资没有绝对的高低,具体取决于技能和行业需求。1.Python在数据科学和机器学习领域可能薪资更高。2.JavaScript在前端和全栈开发中需求大,薪资也可观。3.影响因素包括经验、地理位置、公司规模和特定技能。

如何理解 C 语言中的 !x? 如何理解 C 语言中的 !x? Apr 03, 2025 pm 02:33 PM

!x 的理解!x 是 C 语言中的逻辑非运算符,对 x 的值进行布尔取反,即真变假,假变真。但要注意,C 语言中真假由数值而非布尔类型表示,非零视为真,只有 0 才视为假。因此,!x 对负数的处理与正数相同,都视为真。

H5页面制作是否需要持续维护 H5页面制作是否需要持续维护 Apr 05, 2025 pm 11:27 PM

H5页面需要持续维护,这是因为代码漏洞、浏览器兼容性、性能优化、安全更新和用户体验提升等因素。有效维护的方法包括建立完善的测试体系、使用版本控制工具、定期监控页面性能、收集用户反馈和制定维护计划。

C语言中 sum 是什么意思? C语言中 sum 是什么意思? Apr 03, 2025 pm 02:36 PM

C语言中没有内置的sum函数用于求和,但可以通过以下方法实现:使用循环逐个累加元素;使用指针逐个访问并累加元素;对于大数据量,考虑并行计算。

爱心代码复制粘贴 爱心代码免费复制粘贴手机 爱心代码复制粘贴 爱心代码免费复制粘贴手机 Apr 04, 2025 am 06:48 AM

复制粘贴代码并非不可行,但需谨慎对待。代码中环境、库、版本等依赖项可能与当前项目不匹配,导致错误或不可预料的结果。务必确保上下文一致,包括文件路径、依赖库和 Python 版本。此外,复制粘贴特定库的代码时,可能需要安装该库及其依赖项。常见的错误包括路径错误、版本冲突和代码风格不一致。性能优化需根据代码原用途和约束重新设计或重构。理解并调试复制的代码至关重要,切勿盲目复制粘贴。

如何获取58同城工作页面上的实时申请和浏览人数数据? 如何获取58同城工作页面上的实时申请和浏览人数数据? Apr 05, 2025 am 08:06 AM

如何在爬虫时获取58同城工作页面的动态数据?在使用爬虫工具爬取58同城的某个工作页面时,可能会遇到这样�...

See all articles