Python备份百度博客

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

'''
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()



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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值