最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python實現(xiàn)登陸知乎獲得個人收藏并保存為word文件

 更新時間:2015年03月16日 09:26:56   投稿:junjie  
這篇文章主要介紹了python實現(xiàn)登陸知乎獲得個人收藏并保存為word文件,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下

這個程序其實很早之前就完成了,一直沒有發(fā)出了,趁著最近不是很忙就分享給大家.
使用BeautifulSoup模塊和urllib2模塊實現(xiàn),然后保存成word是使用python docx模塊的,安裝方式網(wǎng)上一搜一大堆,我就不再贅述了.

主要實現(xiàn)的功能是登陸知乎,然后將個人收藏的問題和答案獲取到之后保存為word文檔,以便沒有網(wǎng)絡(luò)的時候可以查閱.當(dāng)然,答案中如果有圖片的話也是可以獲取到的.不過這塊還是有點問題的.等以后有時間了在修改修改吧.

還有就是正則,用的簡直不要太爛…鄙視下自己…

還有,現(xiàn)在是問題的話所有的答案都會保存下來的.看看有時間修改成只保存第一個答案或者收藏頁問題的答案吧.要不然如果收藏的太多了的話保存下來的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
 
#這兒是因為在公司上網(wǎng)的話需要使用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]*</>')
  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)
    ###這一塊弄得太復(fù)雜了 有時間找找看有沒有處理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/?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
    #這兒是當(dāng)時做測試用的,值獲取一個收藏
    #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()

好了,大概就是這樣,大家如果有什么好的建議或者什么的可以再下面留言,我會盡快回復(fù)的.或者在小站的關(guān)于頁面有我的聯(lián)系方式,直接聯(lián)系我就ok.

相關(guān)文章

  • python如何實現(xiàn)圖片轉(zhuǎn)文字

    python如何實現(xiàn)圖片轉(zhuǎn)文字

    這篇文章主要介紹了python如何實現(xiàn)圖片轉(zhuǎn)文字問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • python循環(huán)定時中斷執(zhí)行某一段程序的實例

    python循環(huán)定時中斷執(zhí)行某一段程序的實例

    今天小編就為大家分享一篇python循環(huán)定時中斷執(zhí)行某一段程序的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • Python單例模式實例詳解

    Python單例模式實例詳解

    這篇文章主要介紹了Python單例模式,結(jié)合實例形式分析了單例模式的概念、實現(xiàn)與使用方法、已經(jīng)相關(guān)注意事項,需要的朋友可以參考下
    2017-03-03
  • python-opencv-cv2.threshold()二值化函數(shù)的使用

    python-opencv-cv2.threshold()二值化函數(shù)的使用

    這篇文章主要介紹了python-opencv-cv2.threshold()二值化函數(shù)的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • python中NumPy的安裝與基本操作

    python中NumPy的安裝與基本操作

    Python雖然也提供了array模塊,但其只支持一維數(shù)組,不支持多維數(shù)組,也沒有各種運算函數(shù),因而不適合數(shù)值運算,NumPy的出現(xiàn)彌補了這些不足,這篇文章主要給大家介紹了關(guān)于python中NumPy的安裝與基本操作的相關(guān)資料,需要的朋友可以參考下
    2022-03-03
  • 零基礎(chǔ)寫python爬蟲之抓取糗事百科代碼分享

    零基礎(chǔ)寫python爬蟲之抓取糗事百科代碼分享

    前面我們介紹了如何抓取百度貼吧文章,然后講解了python的神器正則表達式,下面,我們就把2者結(jié)合起來,詳細介紹下,如何來抓取到糗事百科里面的指定內(nèi)容
    2014-11-11
  • python xlwt模塊的使用解析

    python xlwt模塊的使用解析

    這篇文章主要介紹了python xlwt模塊的使用解析,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-04-04
  • Django中使用Celery的教程詳解

    Django中使用Celery的教程詳解

    Django是一個開放源代碼的Web應(yīng)用框架,由Python寫成,Celery是一個基于python開發(fā)的分布式任務(wù)隊列。這篇文章主要介紹了Django中使用Celery教程,需要的朋友可以參考下
    2018-08-08
  • 一文搞懂關(guān)于?sys.argv?的詳解

    一文搞懂關(guān)于?sys.argv?的詳解

    sys.argv?其實就是一個列表,里邊需要用戶傳入的參數(shù),關(guān)鍵就是要明白這參數(shù)是從程序外部輸入的,而非代碼本身的什么地方,要想看到它的效果就應(yīng)該將程序保存了,從外部來運行程序并給出參數(shù),通過本文學(xué)習(xí)你將明白?sys.argv很多知識,感興趣的朋友一起看看吧
    2023-01-01
  • Scrapy基于Python構(gòu)建強大網(wǎng)絡(luò)爬蟲框架實例探究

    Scrapy基于Python構(gòu)建強大網(wǎng)絡(luò)爬蟲框架實例探究

    這篇文章主要為大家介紹了Scrapy基于Python構(gòu)建強大網(wǎng)絡(luò)爬蟲框架實例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01

最新評論

平顺县| 江北区| 太谷县| 凌源市| 从化市| 定兴县| 淄博市| 陵水| 阳泉市| 肥城市| 固始县| 巴林右旗| 茂名市| 监利县| 玛多县| 张掖市| 清徐县| 河西区| 文山县| 永清县| 泗洪县| 盈江县| 湘阴县| 古田县| 北海市| 兰溪市| 如皋市| 新巴尔虎右旗| 梨树县| 玉树县| 开封县| 丰台区| 固安县| 宁国市| 鄯善县| 吉首市| 克拉玛依市| 句容市| 通渭县| 龙游县| 隆回县|