您的位置:首页 > 编程语言 > Python开发

CSDN博客专栏文章批量下载脚本[python实现]

2012-08-08 00:08 1016 查看
最近发现CSDN的blog专栏还是很给力的,毕竟这是一整个系列的文章,学习某方面知识比较容易形成体系,而且前人的经验还是相当有参考价值的。

原先也开了两个,只是工作比较忙,加之lz比较懒,所以没啥人气,囧。

最近看书之余,也会去看看别人的专栏,虽然你看或不看,文章就在那里,但是不能上网的时候还是很蛋疼的

so,花了一个小时,写了个python脚本,只需要填下专栏文章列表某一页url【注意不是文章页面,是列表页面】,就能将整个专栏文章端下来。

分享之,想下整个系列文章的同学动手吧。



目前在win7 + py2.7测试通过,要有python环境哈,linux的同学需dos2unix处理下。

木有python环境的,下个吧,2.7,装一下很快的http://www.python.org/

PS.有很多坑,但是下大部分专栏还是没问题的(譬如文件名存在非法字符暂未处理),没异常处理,都怎么简单怎么来

发现坑的话希望能发我,逐步改进,后续有空的话搞掉python环境依赖&增加图形界面

--------------------------------------------------------------------------------------------------

实现思路:

1.到专栏列表页,正则匹配到最后一页的url

2.生成每页url列表,从第一页到最后一页的url

3.抓每一页,正则匹配到列表页里面文章标题和文章地址

4.下载之

木有python的同学可以用其他语言搞下

---------------------------------------------------------------------------------------------------

使用方法:

1.打开专栏的列表页面,拉到url

例如:http://blog.csdn.net/column/details/wklken4linux.html

图示1:不带页码的(文章太少,就是所有文章列表都木有翻页),以下这个是lz的,o(╯□╰)o



图示2:带页码的 (文章很多,分页了,放心,随便哪页都行,整个系列全端下来)



2.复制url,修改脚本里line 68行,修改first_url变量

3.开始->运行->cmd

cd到脚本所在位置

有配置环境变量的,直接 python download_column.py

没有配置环境变量的,使用 C:\Python27\python.exe download_column.py 【这里路径是装环境时的】

4.过程图:



5.结果:





#version 0.1 基本功能

下载地址: http://www.kuaipan.cn/file/id_43019534898112640.html
#version 0.2 A.修复下载文章中存在非法字符bug B.独立函数,可以批量配置下载C.已下载不会二次下载

下载地址:http://www.kuaipan.cn/file/id_43019534898113708.html

配了一堆,下完了,甚是壮观.................

附上脚本源码:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
#@Author: wklken
#@Mail: wklken@yeah.net
#@Date: 20120807
#@version 0.1
#@desc: base function to download csdn column!

print "begin...."

import urllib2,socket
import re
import os,sys

#该页最后一个中文链接,尾页
p2first = re.compile(ur'下一页</a> <a href="(.*?)">尾页</a>') #html?page=\d+

p2detail = re.compile(ur'<a name="\d+" href="(.*?)" target="_blank">(.*)</a>')

p2title = re.compile(ur'<title>专栏:(.*) - 博客频道 - CSDN.NET</title>')

p2titlereplace = re.compile(r'[\/:*?"<>|]')

def find_url_prefix_maxpage_title(content):
    title = p2title.findall(content,re.X)
    l =  p2first.findall(content,re.X)
    if l and len(l[0].split("=")) == 2:  #存在多页
       return True,l[0].split("="),title[0]
    else:
       return False,(None,None),title[0]

def get_request(url):
    #设置超时  
    socket.setdefaulttimeout(60)  
    #可以加入请求头信息,以便识别
    i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5",  
                "Accept": "text/plain"}   
    req = urllib2.Request(url, headers=i_headers)  
    content = ""
    try:  
        page = urllib2.urlopen(req) 
        #print page.geturl()
        #print page.info().getplist()
        content =  page.read().decode("utf-8")
    except urllib2.HTTPError, e:  
        print "Error Code:", e.code  
    except urllib2.URLError, e:  
        print "Error Reason:", e.reason 
    return content

def gen_urls(url_prefix, max_page):
    for i in range(1,max_page+1):
        yield url_prefix + "=" + str(i)

def download_pages(url, dir_path):
    content = get_request(url)
    l =  p2detail.findall(content,re.X)
    #print l,len(l),l[0]
    for (detail_url, title) in l:
        print "Downloading: ",title,detail_url
        title, num = p2titlereplace.subn("-",title)
        path = dir_path + os.sep + title + ".html"
        if not os.path.exists(path): #只下载新文章,不过老文章修改无法下到,要想全部更新,可以去掉if
            f = open(path,"w")
            f.write(get_request(detail_url).encode("utf-8"))
            f.close()

def get_down(first_url):
    content = get_request(first_url)
    multi_page,(url_prefix, max_apge), title =  find_url_prefix_maxpage_title(content) 

    print title
    title, num = p2titlereplace.subn("-",title)
    dir_path = "./"+title
    if not os.path.exists(dir_path):
        os.mkdir(dir_path)

    if multi_page:
        for url in gen_urls(url_prefix, int(max_apge)):
            print url
            download_pages("http://blog.csdn.net" + url, dir_path)
    else:
        download_pages(first_url, dir_path)    

if __name__ == '__main__':
    #first_url = "http://blog.csdn.net/column/details/novelnorains.html?page=4"
    # first_url = "http://blog.csdn.net/column/details/wklken4ds-alg-py.html"
    # get_down(first_url)
    # sys.exit(0)

    urls = [
    "http://blog.csdn.net/column/details/wklken4ds-alg-py.html", #数据结构和算法python实现,未完
    "http://blog.csdn.net/column/details/wklken4linux.html", #linux新手生存笔记,未完
    ]
    for first_url in urls:
        get_down(first_url)


就这些

懒得动了,歇了

wklken

2012-08-07

http://wklken.sinaapp.com/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: