码迷,mamicode.com
首页 > 编程语言 > 详细

Python脚本自动下载小说

时间:2015-05-28 14:23:38      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:python beautifulsoup 小说

        本人喜欢在网上看小说,一直使用的是小说下载阅读器,可以自动从网上下载想看的小说到本地,比较方便。最近在学习Python的爬虫,受此启发,突然就想到写一个爬取小说内容的脚本玩玩。于是,通过在逐浪上面分析源代码,找出结构特点之后,写了一个可以爬取逐浪上小说内容的脚本。

        具体实现功能如下:输入小说目录页的url之后,脚本会自动分析目录页,提取小说的章节名和章节链接地址。然后再从章节链接地址逐个提取章节内容。现阶段只是将小说从第一章开始,每次提取一章内容,回车之后提取下一章内容。其他网站的结果可能有不同,需要做一定修改。在逐浪测试过正常。

        分享此代码,一是做个记录,方便自己以后回顾。二么也想抛砖引玉,希望各路大神不吝赐教。

        下面是我用来测试的页面:http://book.zhulang.com/263736/

效果如下:

技术分享


实现的源代码如下,请各位指教:

#-*-coding:utf8-*-
#!/usr/bin/python
# Python:      2.7.8
# Platform:    Windows
# Program:     Get Novels From Internet
# Author:      wucl
# Description: Get Novels
# Version:     1.0
# History:     2015.5.27  完成目录和url提取
#              2015.5.28  完成目录中正则提取第*章,提取出章节链接并下载。在逐浪测试下载无误。

from bs4 import BeautifulSoup
import urllib2,re

def get_menu(url):
    """Get chapter name and its url"""
    user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0"
    headers = {‘User-Agent‘:user_agent}
    req = urllib2.Request(url,headers = headers)
    page = urllib2.urlopen(req).read()
    soup = BeautifulSoup(page)
    novel = soup.find_all(‘title‘)[0].text.split(‘_‘)[0]     # 提取小说名
    menu = []
    all_text = soup.find_all(‘a‘,target="_blank")   # 提取记载有小说章节名和链接地址的模块
    regex=re.compile(ur‘\u7b2c.+\u7ae0‘)          # 中文正则匹配第..章,去除不必要的链接
    for title in all_text:
        if re.findall(regex,title.text):
            name = title.text
            x = [name,title[‘href‘]]
            menu.append(x)       # 把记载有小说章节名和链接地址的列表插入列表中                
    return menu,novel

def get_chapter(name,url):
    """Get every chapter in menu"""
    html=urllib2.urlopen(url).read()
    soup=BeautifulSoup(html)
    content=soup.find_all(‘p‘)     # 提取小说正文
    return content[0].text
    
    
    

if __name__=="__main__":
    url=raw_input("""Input the main page‘s url of the novel in ZhuLang\n        Then Press Enter to Continue\n""")
    if url:
        menu,title=get_menu(url)
        print title,str(len(menu))+‘\n     Press Enter To Continue   \n‘     # 输出获取到的小说名和章节数
        for i in menu:
            chapter=get_chapter(i[0],i[1])
            raw_input()
            print ‘\n‘+i[0]+‘\n‘        
            print chapter
            print ‘\n‘


本文出自 “载酒仗剑江湖行” 博客,请务必保留此出处http://wucl202000.blog.51cto.com/4687508/1655858

Python脚本自动下载小说

标签:python beautifulsoup 小说

原文地址:http://wucl202000.blog.51cto.com/4687508/1655858

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!