`
yexin218
  • 浏览: 959017 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

Python备份百度博客

阅读更多
开始学Python,就看看urllib模块,然后参考网上的一些资料,自己动手写一个,新手完全不顾效率和程序的美观,只想试下。最难的部分在于正则,看了一些资料,还是不会,只好凑合使用,莫见笑~

'''
Created on Apr 22, 2010

@author: Leyond
'''

import urllib
import re
def downloadpage(url_hi ='http://hi.baidu.com/',user ='codedeveloper', blogUrl = '/blog/item/809ad16011b3196c0d33fa5f.html'):
    url = url_hi +user+ blogUrl
    nFail =0
    while nFail < 3:
        try:
            sock = urllib.urlopen(url)
            htmlSource = sock.read()
            #htmlContent = re.findall(r"<div id=\"m_blog\".*?>",htmlSource,re.I)
           # print htmlContent
            htmlSourceNew = htmlSource.replace("\n"," ")
            htmlContent = re.findall(r"<div id=\"m_blog\".*?<\/div><\/td><\/tr><\/table>",htmlSourceNew,re.I)
            user += '/%s' % (blogUrl[11:])

            myfile = file(user,'w')
            myfile.write("<html><body>"+htmlContent[0]+"</body></html>")#保存有效部分
            myfile.close()
            urls = re.findall(r"var.*pre.*?/blog/item/.*?html",htmlSource,re.I)
            if(len(urls)==1):
                blogUrl = re.findall(r"/blog/item/.*?html",urls[0],re.I)
                htmlUrl = 'http://hi.baidu.com/' + user + blogUrl[0]
                print htmlUrl
                downloadpage(blogUrl = blogUrl[0])#递归你所有的文章
            else:
                break
            

            sock.close()
            return
        except:
            nFail += 1
            print 'download blog fail: %s' % (blogUrl)
      
downloadpage()



用之前,需要在文件所在目录新建一个目录,例如我的博客就是codedeveloper,使用这段程序,需要更改两个参数:

downloadpage(user = "yours",blogUrl = '/blog/item/yournewestblogurl.html')
其中user那里指的是你的用户名,yournewestblogurl说的是你最新那篇博文的地址~
等我进一步学习,我在慢慢改善~ 比如使用线程,wget下载等,还有就是处理图片问题。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics