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

Python實(shí)現(xiàn)新浪博客備份的方法

 更新時(shí)間:2016年04月27日 11:35:30   作者:阿涵-_-  
這篇文章主要介紹了Python實(shí)現(xiàn)新浪博客備份的方法,涉及Python正則操作,字符串操作及文本操作的相關(guān)技巧,需要的朋友可以參考下

本文實(shí)例講述了Python實(shí)現(xiàn)新浪博客備份的方法。分享給大家供大家參考,具體如下:

Python2.7.2版本實(shí)現(xiàn),推薦在IDE中運(yùn)行。

# -*- coding:UTF-8 -*- #
'''
Created on 2011-12-18
@author: Ahan
'''
import re
import sys
import os
import time
import socket
import locale
import datetime
import codecs
from urllib import urlopen
#正則表達(dá)式定義
#匹配博文目錄鏈接
pattern1=u"""<a href="(http:.*?)">博文目錄</a>"""
prog1 = re.compile(pattern1)
#匹配博文標(biāo)題鏈接
pattern2=u"""<a title="(.*?)" target="_blank" href="(.*?)">.*?</a>"""
prog2=re.compile(pattern2)
#匹配下一頁(yè)鏈接
pattern3=u"""<a href="([^"]+)" title="[^"]+">下一頁(yè)"""
prog3=re.compile(pattern3)
#匹配正文部分
pattern4=u"""<!--博文正文 begin -->[\\s\\S]*?<!-- 正文結(jié)束 -->"""
prog4=re.compile(pattern4)
#匹配正文圖片鏈接
pattern5=u"""(src="[^"]+"( real_src ="([^"]+)"))"""
prog5=re.compile(pattern5)
def read_date_from_url(url):
  """以Unicode形式返回從url上讀取的所有數(shù)據(jù)
  """
  try:
    data = ""
    request = urlopen(url)
    while True:
      s = request.read(1024)
      if not s:
        break
      data += s
    return unicode(data)
  except:
    print '讀取數(shù)據(jù)時(shí)出錯(cuò)'
    print "Unexpected error:", sys.exc_info()[0],sys.exc_info()[1]
    return None
  finally:
    if request:
      request.close()
def save_to_file(url,filename,blog_address):
  """url為博文地址,filename為要保存的文件名,默認(rèn)后綴為html
  """
  #如果文件夾不存在則創(chuàng)建文件夾
  if os.path.exists(blog_address)==False:
    os.makedirs(blog_address)
  #去掉文件名中的非法字符
  filename=ReplaceBadCharOfFileName(filename)
  file_no=0
  while os.path.isfile(blog_address+'/'+filename+'.html')==True:
    filename=filename+'('+file_no.__str__()+')'
    file_no+=1
  text = read_date_from_url(url)
  text=_filter(text)
  #將圖片保存到本地
  result=prog5.findall(text)
  i=1
  for pic in result:
    folder=blog_address+'/'+filename+'/'
    pic_name='image'+i.__str__()+'.gif' 
    if os.path.exists(folder)==False:
      os.makedirs(folder)
    try:
      url_file = urlopen(pic[2])
      pic_file = codecs.open(folder+pic_name,'wb')
      while True:
        s = url_file.read(1024)
        if not s:
          break
        pic_file.write(s)
      pic_file.close()
      url_file.close()
    except:
      print '噢,保存圖片的時(shí)候出現(xiàn)問題了,跳過此張圖片...'
      print "Unexpected error:", sys.exc_info()[0],sys.exc_info()[1]
    else:
      print '保存圖片成功...'
      #替換正文中的圖片地址
      text=text.replace(pic[0],unicode("src=\"" + filename + "/" + pic_name + "\"" + pic[1]),1)
      i=i+1
  blog_file = codecs.open(blog_address+'/'+filename+'.html','wb')
  blog_file.write(text)
  blog_file.close()
#提取文本中的正文部分
def _filter(t):
  """提取文本中的正文部分,返回Unicode形式的字符串
  """
  result=prog4.search(t)
  if result is not None:
    return u'<html><head></head><body>' + unicode(result.group()) + u'</dody></html>'
  else:
    raise Exception('噢,提取正文出錯(cuò)了……')
#去掉文件名的不合法字符 
def ReplaceBadCharOfFileName(filename):
  filename=filename.replace("&nbsp;","")
  filename=filename.replace("\\", "")
  filename=filename.replace("/", "")
  filename=filename.replace(":", "")
  filename=filename.replace("*", "")
  filename=filename.replace("?", "")
  filename=filename.replace("<", "")
  filename=filename.replace(">", "")
  filename=filename.replace("|", "")
  filename=filename.replace("&","")
  filename=filename.replace(";","")
  return filename
#主函數(shù)
if __name__ == '__main__':
  #準(zhǔn)備階段
  blog_no=1#博文編號(hào)
  begin=1#起始博文
  end=0#結(jié)束博文
  page=0#頁(yè)碼
  saved=0#成功保存的篇數(shù)
  timeout = 60*5#超時(shí)設(shè)為5分鐘
  socket.setdefaulttimeout(timeout)#這里對(duì)整個(gè)socket層設(shè)置超時(shí)時(shí)間。后續(xù)文件中如果再使用到socket,不必再設(shè)置
  blog_address=raw_input("請(qǐng)輸入您的博客地址(輸入最后部分即可,比如您的博客地址是http://blog.sina.com.cn/jiangafu,只要輸入jiangafu):")
  blog_address=blog_address.replace('\r','')
  begin=raw_input('從第幾篇開始:')  
  begin=locale.atoi(begin)
  while begin<=0:
    begin=raw_input('請(qǐng)輸入大于0的數(shù):')
    begin=locale.atoi(begin)
  end=raw_input('到第幾篇結(jié)束(到最后請(qǐng)輸入0):')
  end=locale.atoi(end)
  while end<0:
    end=raw_input('請(qǐng)輸入大于等于0的數(shù):')
    end=locale.atoi(end)
  if end==0:
    print '您的博客地址是:http://blog.sina.com.cn/'+blog_address+',保存第'+begin.__str__()+'篇到最后一篇博文'
  else:
    print '您的博客地址是:http://blog.sina.com.cn/'+blog_address+',保存第'+begin.__str__()+'篇到第'\
       +end.__str__()+'篇的博文'
  starttime = datetime.datetime.now()
  text=read_date_from_url('http://blog.sina.com.cn/'+blog_address)
  time.sleep(0.5)
  #提取“博文目錄”的url
  result = prog1.search(text)
  if result is not None:
    print '博文目錄地址:' , result.group(1)
    text=read_date_from_url(result.group(1))
    time.sleep(0.4)
  else:
    print '提取博文目錄地址失敗'
    #終止程序運(yùn)行
    sys.exit()
  #查找每一頁(yè)的全部博文,分析、提取、保存 
  while True:
    page+=1
    print '開始備份第' , page , '頁(yè)'
    #匹配該頁(yè)的所有博文地址
    result=prog2.findall(text)
    #循環(huán)下載本頁(yè)每篇博文
    for blog in result: 
      if blog_no < begin:
        blog_no += 1
      elif end != 0 and blog_no > end:
        break
      else:
        try:
          save_to_file(blog[1],unicode(blog[0]),blog_address)
        except:
          print '噢,保存第',blog_no,'篇博文',blog[0],'的時(shí)候出現(xiàn)問題了,跳過...'
          blog_no += 1
          print "Unexpected error:", sys.exc_info()[0],sys.exc_info()[1]
        else:
          print '成功保存了第', blog_no, '篇博文:', blog[0]
          blog_no += 1
          saved += 1
          time.sleep(0.4)
    #判斷是否有下一頁(yè)
    result = prog3.search(text)
    if result is not None:
      text = read_date_from_url(result.group(1))
    else:
      print '這是最后一頁(yè)'
      break
  print '博客備份完成一共備份',saved,'篇博文'
  print '共用時(shí):',datetime.datetime.now() - starttime
  raw_input('按回車鍵退出...')

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • Windows下Anaconda下載安裝與配置教程分享

    Windows下Anaconda下載安裝與配置教程分享

    這篇文章主要介紹了Windows下Anaconda下載安裝與配置教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • pytorch建立mobilenetV3-ssd網(wǎng)絡(luò)并進(jìn)行訓(xùn)練與預(yù)測(cè)方式

    pytorch建立mobilenetV3-ssd網(wǎng)絡(luò)并進(jìn)行訓(xùn)練與預(yù)測(cè)方式

    這篇文章主要介紹了pytorch建立mobilenetV3-ssd網(wǎng)絡(luò)并進(jìn)行訓(xùn)練與預(yù)測(cè)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • tensorboard實(shí)現(xiàn)同時(shí)顯示訓(xùn)練曲線和測(cè)試曲線

    tensorboard實(shí)現(xiàn)同時(shí)顯示訓(xùn)練曲線和測(cè)試曲線

    今天小編就為大家分享一篇tensorboard實(shí)現(xiàn)同時(shí)顯示訓(xùn)練曲線和測(cè)試曲線,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2020-01-01
  • python沒有g(shù)pu,如何改用cpu跑代碼

    python沒有g(shù)pu,如何改用cpu跑代碼

    這篇文章主要介紹了python沒有g(shù)pu,如何改用cpu跑代碼?今天小編就為大家分享一下解決方案。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • 使用Python實(shí)現(xiàn)SSH隧道界面功能

    使用Python實(shí)現(xiàn)SSH隧道界面功能

    這篇文章主要介紹了使用Python實(shí)現(xiàn)一個(gè)SSH隧道界面功能,界面使用tkinter實(shí)現(xiàn),左邊是輸入隧道的信息,右邊為歷史列表,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2022-02-02
  • python將圖片轉(zhuǎn)為矢量圖的方法步驟

    python將圖片轉(zhuǎn)為矢量圖的方法步驟

    這篇文章主要介紹了python將圖片轉(zhuǎn)為矢量圖的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • Python?SQLAlchemy與數(shù)據(jù)庫(kù)交互操作完整指南

    Python?SQLAlchemy與數(shù)據(jù)庫(kù)交互操作完整指南

    SQLAlchemy 是一個(gè)強(qiáng)大的 Python 庫(kù),用于數(shù)據(jù)庫(kù)操作,無(wú)論是簡(jiǎn)單的數(shù)據(jù)存儲(chǔ)還是復(fù)雜的數(shù)據(jù)管理,SQLAlchemy 都提供了多種方法來(lái)處理數(shù)據(jù)庫(kù),本文將全面介紹 SQLAlchemy的基本用法以及各種操作的示例代碼
    2024-01-01
  • Django的get_absolute_url方法的使用

    Django的get_absolute_url方法的使用

    本文主要介紹了Django的get_absolute_url方法的使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • Python讀取文件的8種常用方式

    Python讀取文件的8種常用方式

    這篇文章主要給大家介紹了關(guān)于Python讀取文件的8種常用方式,在編程語(yǔ)言中,文件讀寫是最常見的IO操作,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下
    2023-09-09
  • Python3之文件讀寫操作的實(shí)例講解

    Python3之文件讀寫操作的實(shí)例講解

    下面小編就為大家分享一篇Python3之文件讀寫操作的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2018-01-01

最新評(píng)論

安泽县| 汶上县| 丰镇市| 高清| 政和县| 雷州市| 饶阳县| 宁远县| 高青县| 防城港市| 三河市| 灵武市| 筠连县| 枝江市| 潼南县| 新丰县| 大洼县| 安塞县| 宣恩县| 外汇| 藁城市| 电白县| 华坪县| 龙江县| 乐昌市| 绥宁县| 忻城县| 长白| 洞口县| 灵台县| 宜君县| 孝昌县| 吴川市| 图们市| 芦溪县| 宾阳县| 南京市| 辽中县| 湘西| 分宜县| 民乐县|