python爬取小说《元尊》

  • A+
所属分类:python 未分类

python爬取小说《元尊》

《元尊》是天蚕土豆的新连载小说。为了方便阅读,下面将会演示提取http://doupocangqiong1.com/17316/ 站点中《元尊》 目前所有章节并整合到txt文件的全过程。

目录提取

首先,我们需要从总的章节列表中,提取出所有章节的名称以及对应的链接地址。

  • F12打开开发者工具
  • 鼠标点击下图所示1的位置的箭头,进行选取操作。
  • 鼠标点击下图所示2的位置进行选取
  • 鼠标在下图所示3的位置右键,在弹出的菜单中依次选择Copy->Copy selector

python爬取小说《元尊》

  • 将刚才拷贝的数据粘贴到任一文件中,进行临时记录。
    如果操作正确,应该是会得到类似body > section > div.card.mt20.fulldir > div.body > ul > li:nth-child(5) > a的一串字符。

  • 将刚才的字符稍作修改,修改成body > section > div.card.mt20.fulldir > div.body > ul > li > a并用到python代码中,即可得到每个章节的相关信息。

编码提取目录函数

基于章节信息html格式如下

<a href="/17316/5.html" title="元尊 第一章 蟒雀吞龙" target="_blank">第一章 蟒雀吞龙</a>

href为对应章节的地址。
title为对应章节的名称。
编写针对上述格式的python代码,即可提取出所有的章节目录。

def get_urls():
    res = requests.get('http://doupocangqiong1.com/17316/', headers=headers).text
    soup = BeautifulSoup(res, "lxml")
    pages = soup.select('body > section > div.card.mt20.fulldir > div.body > ul > li > a')
    for pageInfo in pages:
        link = 'http://doupocangqiong1.com{}'.format(pageInfo.get('href'))
        title = pageInfo.get('title')

尝试获取章节内容

先前我们已经获取到了章节目录的地址。我们先尝试直接通过章节目录地址能否直接获取到章节内容。执行以下的python代码进行尝试。


import requests from bs4 import BeautifulSoup headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)\ Chrome/59.0.3071.112 Safari/537.36 Vivaldi/1.91.867.48' } def get_urls(): res = requests.get('http://doupocangqiong1.com/17316/', headers=headers).text soup = BeautifulSoup(res, "lxml") pages = soup.select('body > section > div.card.mt20.fulldir > div.body > ul > li > a') for pageInfo in pages: link = 'http://doupocangqiong1.com{}'.format(pageInfo.get('href')) get_info(link) break def get_info(url): res = requests.get(url, headers=headers,stream=True) soup = BeautifulSoup(res.text, "lxml") content = soup.select('#chaptercontent') print(content) get_urls()

执行结果如下图:
python爬取小说《元尊》

从上图看出,我们并不能直接从章节地址获取到文章内容。那该如何获取呢?

理清数据来源

我们在浏览器中输入第一章的地址 http://doupocangqiong1.com/17316/5.html ,并打开开发者模式。刷新页面。按下图所示的步骤进行操作。
python爬取小说《元尊》

我们可以在上图5的位置,看到文章内容的数据。

我们再切换到headers选项卡,查看Request URL的信息,如下图:
python爬取小说《元尊》

现在我们需要思考的就是Request URL中的地址是怎么来的?

提取章节具体内容

还记的我们之前尝试直接获取章节内容的时候提示了“正在转码,请稍后”的文字信息吗。我们再执行如下代码,跟之前的尝试性代码相比,只是改了打印而已。


import requests from bs4 import BeautifulSoup headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)\ Chrome/59.0.3071.112 Safari/537.36 Vivaldi/1.91.867.48' } def get_urls(): res = requests.get('http://doupocangqiong1.com/17316/', headers=headers).text soup = BeautifulSoup(res, "lxml") pages = soup.select('body > section > div.card.mt20.fulldir > div.body > ul > li > a') for pageInfo in pages: link = 'http://doupocangqiong1.com{}'.format(pageInfo.get('href')) get_info(link) break def get_info(url): res = requests.get(url, headers=headers,stream=True) print(res.text) get_urls()

代码执行结果如下:

<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="utf-8" />
    <title>新书感言 - 元尊 - 元尊 E小说 - 斗破苍穹小说网</title>
    <meta name="keywords" content="新书感言,元尊小说,元尊 E小说,斗破苍穹小说网" />
    <meta name="description" content="《元尊》新书感言,斗破苍穹小说网提供天蚕土豆小说《元尊》最新章节的搜索和转码阅读,更新超级快, 元尊无弹窗阅读,页面干净清爽,希望大家收藏!" />
        <link rel="canonical" href="http://doupocangqiong1.com/17316/1.html"/>
    <meta name="author" content="斗破苍穹小说网">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="renderer" content="webkit">
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta http-equiv="Cache-Control" content="no-transform " />
<link rel="shortcut icon" type="image/ico" href="/favicon.ico" />
<meta name="applicable-device" content="pc">
<meta http-equiv="mobile-agent" content="format=html5; url=http://m.doupocangqiong1.com/17316/1.html">
<link rel="stylesheet" href="http://s.dpcq1.net/public/ptcms/s_d98e2ebc672087ddba0be093199273e2.css?g=pccss" />
<!--[if lt IE 9]>
<script src="http://s.dpcq1.net/template/defaultv1/public/script/html5shiv.min.js"></script>
<![endif]-->
<script type="text/javascript" src="http://s.dpcq1.net/public/ptcms/s_pc_novelsearch_chapter_read.js"></script>

</head>
<body class="readpage">
<div class="frame-header">
    <div class="frame-header-content">
        <div class="logo"><a href="http://doupocangqiong1.com" title="斗破苍穹小说网"><img src="/template/defaultv1/public/image/logo.png" alt="python爬取小说《元尊》" alt="斗破苍穹小说网" /></a></div>
        <div class="searchbox">
            <form action="/search.html" name="search-form" method="get">
                <input type="text" class="text" name="searchkey" value="元尊" onfocus="(function(o){if(o.value=='元尊'){o.value='';o.className='focus'}})(this);" onblur="(function(o){if(o.value==''){o.value='元尊';o.className='';}})(this)" autocomplete="off" />
                <button type="submit" class="searchbtn">搜书</button>
            </form>
        </div>
        <div class="frame-operate">
            <div class="frame-btn">
                <a href="/17316/0.html" class="btn btn-primary btn-sm" title="第两百一十三章 罗松5 yqxs.cc"><i class="pticon pticon-chevron-left"></i> 上一章</a>
                <a href="/17316/" class="btn btn-default" title="元尊"><i class="pticon pticon-list"></i> 目录</a>
                <a href="/17316/2.html" class="btn btn-primary" title="更新预告一 15点更新第一章,敬请期待!">下一章 <i class="pticon pticon-chevron-right"></i></a>
                <a href="/user/mark/add.html?novelid=17316&chapterid=1" class="btn btn-danger" target="_blank"><i class="pticon pticon-bookmark"></i> 书签</a>
                <a href="/17316/k423011.html" class="btn btn-success" title="E小说 新书感言"><i class="pticon pticon-globe"></i> 源网站</a>
            </div>
            <div class="frame-source">
                <div class="dropmenu">
                    <span class="tri"></span>
                    <ul class="dropmenu-item">
                                                <li><a href="javascript:void(0);" style="" title="元尊 E小说 新书感言">E小说</a></li>
                                                <li><a href="/17316/t422909.html" style="" title="元尊 纵横中文 新书感言">纵横中文</a></li>
                                                <li><a href="/17316/t423401.html" style="" title="元尊 再读读 新书感言">再读读</a></li>
                                                <li><a href="/17316/t425158.html" style="" title="元尊 大海中文 新书感言">大海中文</a></li>
                                                <li><a href="/17316/t425445.html" style="" title="元尊 少年文学 新书感言">少年文学</a></li>
                                            </ul>
                </div>
            </div>
        </div>
    </div>
</div>
<section class="readpage" >
    <div class="readbox">
        <article>
            <div class="title">
                <h1><a href="/17316/1.html" title="元尊 新书感言">元尊 新书感言</a></h1>
                <div class="info">
                    <span>小说:<a href="/17316/" title="元尊">元尊</a></span>
                    <span>作者:<a href="/author/%E5%A4%A9%E8%9A%95%E5%9C%9F%E8%B1%86/" title="天蚕土豆 作品大全">天蚕土豆</a></span>
                    <span>更新时间:2017-09-14 20:13:09</span>
                    <span>源网站:<a href="/17316/k423011.html" title="新书感言 E小说" rel="nofollow">E小说</a></span>
                 </div>
            </div>
            <div class="pagetopad1" style="padding-top:10px;text-align: center;">
            <script type="text/javascript">showads("pagetopad1");</script>
            </div>
            <div class="content" id="chaptercontent">
                <div class="loading" style="text-align:Center;padding:50px 0"><img src="/public/image/loading.gif" alt="python爬取小说《元尊》"><br/>正在转码,请稍后......</div>            </div>
                        <div class="pagebottomad1" style="text-align: center;">
            <script type="text/javascript">showads("pagebottomad1");</script>
            </div>
            <div class="info bottominfo">
                为更好的阅读体验,本站章节内容基于百度转码进行转码展示,如有问题请您到源站阅读, <a href="https://www.baidu.com/duty/wise/tc_siteapp.html" rel="nofollow">转码声明</a>。<br />
                <a href="http://doupocangqiong1.com" title="斗破苍穹小说网">斗破苍穹小说网</a>邀请您进入最专业的<a href="http://doupocangqiong1.com" title="小说搜索">小说搜索</a>网站阅读<a href="/17316/" title="元尊">元尊</a>,<a href="/17316/list.html" title="元尊">元尊最新章节</a>,<a href="/17316/list_exiaoshuo/" title="元尊">元尊 E小说</a>!
            </div>
        </article>
        <div class="operate">
            <ul>
                <li><a href="/17316/0.html" title="第两百一十三章 罗松5 yqxs.cc"><i class="pticon pticon-chevron-left"></i> 上一章</a></li>
                <li><a href="/17316/" title="元尊"><i class="pticon pticon-list"></i> 目录</a></li>
                <li class="last"><a href="/17316/2.html" title="更新预告一 15点更新第一章,敬请期待!">下一章 <i class="pticon pticon-chevron-right"></i></a></li>
            </ul>
        </div>
        <div class="readingTips">
            可以使用回车、←→快捷键阅读
            <div class="readingSwitch none"><span class="readingSwitch_Btn active"></span>开启瀑布流阅读
            </div>
        </div>
        <article>
            <div class="info bottominfo" style="padding:0;padding-bottom:50px;margin-top: 0;background-color: #f6f4ec;">
                <nav style="background-color: #f6f4ec;">
                    <ul class="clearfix">
                        <li>换源阅读</li>
                    </ul>
                </nav>
                <ul class="chapterlist">
                                        <li>
                        <span class="n">
                            <a href="/17316/t422909.html" target="_self" title="元尊 纵横中文 新书感言"  style="color: #000;">元尊 新书感言</a>
                        </span>
                        <span class="t">09-14 15:35</span>
                        <span class="s">
                                纵横中文                        </span>
                    </li>
                                        <li>
                        <span class="n">
                            <a href="/17316/t423011.html" target="_self" title="元尊 E小说 新书感言"  style="color: #000;">元尊 新书感言</a>
                        </span>
                        <span class="t">09-14 20:09</span>
                        <span class="s">
                                E小说                     </span>
                    </li>
                                        <li>
                        <span class="n">
                            <a href="/17316/t423401.html" target="_self" title="元尊 再读读 新书感言"  style="color: #000;">元尊 新书感言</a>
                        </span>
                        <span class="t">09-15 15:05</span>
                        <span class="s">
                                再读读                     </span>
                    </li>
                                        <li>
                        <span class="n">
                            <a href="/17316/t425158.html" target="_self" title="元尊 大海中文 新书感言"  style="color: #000;">元尊 新书感言</a>
                        </span>
                        <span class="t">09-19 20:09</span>
                        <span class="s">
                                大海中文                        </span>
                    </li>
                                        <li>
                        <span class="n">
                            <a href="/17316/t425445.html" target="_self" title="元尊 少年文学 新书感言"  style="color: #000;">元尊 新书感言</a>
                        </span>
                        <span class="t">09-20 15:37</span>
                        <span class="s">
                                少年文学                        </span>
                    </li>
                                    </ul>
            </div>
        </article>
    </div>
</section>
<footer>
    <div class="copyright w-all tac">
                        <a href="/page/index/detail.html?id=1&key=about" title="关于我们">关于我们</a>    
                <a href="/page/index/detail.html?id=3&key=disdaimer" title="免责声明">免责声明</a>    
                <a href="/page/index/detail.html?id=6&key=privacy" title="隐私条款">隐私条款</a>    
                <a href="/page/index/detail.html?id=4&key=spider" title="蜘蛛协议">蜘蛛协议</a>    
                <a href="/page/index/detail.html?id=7&key=employ" title="申请收录">申请收录</a>    
                <a href="/page/index/detail.html?id=5&key=contact" title="联系我们">联系我们</a>    
                <a href="/sitemap/index.xml" title="sitemap" target="_blank">Sitemap</a>
        <br />
        Copyright © 2009-2018 <a href="http://doupocangqiong1.com" target="_blank" title="斗破苍穹小说网">斗破苍穹小说网</a> All Rights Reserved .版权所有斗破苍穹小说网,沪ICP备16005125号-3。<br />
        本站内容系斗破苍穹小说网根据您的指令搜索各大小说站得到的链接列表,不代表斗破苍穹小说网赞成被搜索网站的内容或立场<br />
        如果版权人认为在本站放置您的作品有损您的利益,请发邮件至qtshucom#163.com,本站确认后将会立即删除。<br />
        <br>
    </div>
</footer>
<div class="gotop"><i class="pticon pticon-chevron-up"></i></div>
<script type="text/javascript">var g_imgurl="http://pic.dpcq1.net";var g_resurl="http://s.dpcq1.net";</script>
<script type="text/javascript" src="http://s.dpcq1.net/public/ptcms/s_c8307a5b8d392c73baddecca38d4bd4e.js?g=pcjs"></script>
<script type="text/javascript">
    document.onkeydown = gopage;
    var prevpage = "/17316/0.html";
    var nextpage = "/17316/2.html";
    var gotobook = "/17316/";
    function gopage() {
        var event = event ? event : window.event;
        if (event.keyCode == 37) location = prevpage;
        if (event.keyCode == 39) location = nextpage;
        if (event.keyCode == 13) location = gotobook;
    }
    window.onerror = function () {
        return true;
    };
    $(function(){
        if(location.search.indexOf('?url')===-1){
            window.history.replaceState(null,$('title').text(),'/17316/1.html?url='+atob('aHR0cHM6Ly93d3cuendkYS5jb20veXVhbnp1bi8xMTE5MzIxNS8='));
        }
    })
        $.get('/novelsearch/reader/transcode/siteid/34/url/aHR0cHM6Ly93d3cuendkYS5jb20veXVhbnp1bi8xMTE5MzIxNS8=',{},function(res){
        $('#chaptercontent').html(res.info);
    });
    $(function () {
        $('.readingSwitch_Btn').on('click',function(){
            if($(this).is('.active')){
                $(this).removeClass('active');
            }else{
                $(this).addClass('active');
            }
        })
    })
        $pt.page.updatemark('17316','1');
</script>
<div>
<script type="text/javascript">showads("footerscript");showads("footertongji");</script>
</div>
</body>
</html>

从打印结果来看,我们可以发现,里面包含了一段非常关键的javaScript代码。

$(function(){
        if(location.search.indexOf('?url')===-1){
            window.history.replaceState(null,$('title').text(),'/17316/1.html?url='+atob('aHR0cHM6Ly93d3cuendkYS5jb20veXVhbnp1bi8xMTE5MzIxNS8='));
        }
    })
        $.get('/novelsearch/reader/transcode/siteid/34/url/aHR0cHM6Ly93d3cuendkYS5jb20veXVhbnp1bi8xMTE5MzIxNS8=',{},function(res){
        $('#chaptercontent').html(res.info);
    });

在这段代码中,居然包含了我们之前一直不知道哪里来的Request URL。至此,我们终于找到了其来源!

因此,我们可以通过获取到的网页source code,并提取出get部位的请求信息。
编写针对性的python代码获取请求链接,python代码如下(url为从章节目录提取到的各章节页面地址):

def get_info(url):
    res = requests.get(url, headers=headers,stream=True)
    regex1 = re.compile(r'get\(\'(.*?)\',', re.IGNORECASE|re.S)
    wh = regex1.findall(res.text)
    contentLink = 'http://doupocangqiong1.com{}'.format(wh[0])
    print(contentLink)

完整代码


import requests import re import json import time from bs4 import BeautifulSoup headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)\ Chrome/59.0.3071.112 Safari/537.36 Vivaldi/1.91.867.48' } allLinkList = {} def get_urls(): res = requests.get('http://doupocangqiong1.com/17316/', headers=headers).text # print(res) soup = BeautifulSoup(res, "lxml") pages = soup.select('body > section > div.card.mt20.fulldir > div.body > ul > li > a') for pageInfo in pages: link = 'http://doupocangqiong1.com{}'.format(pageInfo.get('href')) title = pageInfo.get('title') if allLinkList.get(title) == None: allLinkList[title] = link print(link, title) f.write(title + '\n') get_info(link) time.sleep(0.05) def get_info(url): res = requests.get(url, headers=headers,stream=True) regex1 = re.compile(r'get\(\'(.*?)\',', re.IGNORECASE|re.S) wh = regex1.findall(res.text) contentLink = 'http://doupocangqiong1.com{}'.format(wh[0]) print(contentLink) get_content(contentLink) def get_content(url): res = requests.get(url, headers=headers).text dic = json.loads(res) content = dic.get('info') content = content.replace(' ', ' ').replace('/p>', '').replace('<!--', '').replace('←', '') content = content.replace('<br/><br/>', '\n') f.write(content + '\n') # print(content) f = open("元尊.txt", 'w') get_urls() f.close() print("爬取小说《元尊》完成")

执行结果图

python爬取小说《元尊》

python爬取小说《元尊》

python爬取小说《元尊》

这样就有可以愉快的阅读了。(●'◡'●)

百分购

发表评论

您必须才能发表评论!