【Python】简单实现爬取小说《天龙八部》,并在页面本地访问

背景

很多人说学习爬虫是提升自己的一个非常好的方法,所以有了第一次使用爬虫,水平有限,依葫芦画瓢,主要作为学习的记录。

思路

  1. 使用python的requests模块获取页面信息
  2. 通过re模块(正则表达式)取出需要的内容(小说标题,正文)
  3. 通过MysqlDB模块入库
  4. 使用webpy模块生成访问页面

最终的效果图

下面是效果图,简单实现了点击上一页、下一页翻页的功能:

目录结构

目录结构如下:

D:\PROJECT\SPIDER
│  fiction_spider.py
│  webapp.py

└─template
        index.html

爬取信息及入库示例代码

#coding:utf-8
#fiction_spider.py
import requests import re import MySQLdb def get_title(): html = requests.get('http://www.jinyongwang.com/tian/').content rem = r'<li><a href="(.*?)">(.*?)</a>' return re.findall(rem,html) def get_content(url): html = requests.get('http://www.jinyongwang.com/'+url).content #print html matchs_p = r'<p>(.*?)</p><script.*?' data = re.findall(matchs_p, html) return data[0] if __name__ == '__main__': a = MySQLdb.connect(host='10.1.*.*', port=3306, user='user', passwd='passwd', db='testdb', charset='utf8') for i in get_title(): cur = a.cursor() print i[1] print i[0] sqli = 'INSERT INTO `fiction` (`title`, `content`) VALUES ("%s","%s" )'%(i[1],get_content(i[0])) cur.execute(sqli) cur.close() a.commit() a.close()

生成访问页面示例代码

#coding:utf-8
#webapp.py
import web import re urls = ('/(.*)','Index') db = web.database(dbn = 'mysql',host='10.1.*.*', port=3306, user='user', passwd='passwd', db='testdb', charset='utf8') render = web.template.render('template') class Index: def GET(self,html): id = re.findall('(.*?).html',html)[0] print id data = db.query("select * from fiction where id=%s"%id) return render.index(data[0],id) if __name__ == '__main__': web.application(urls,globals()).run()

页面访问的index.html内容如下:

$def with(data,s)
<meta charset="utf-8"/>
<title>$:data.title</title>
<h1>$:data.title</h1>
<div style="margin:0px auto;text-align:center;">
<a href="$:(int(s)-1).html">上一页</a>
<a href="$:(int(s)+1).html">下一页</a>
</div>
$:data.content
<br>
<div style="margin:0px auto;text-align:center;">
<a href="$:(int(s)-1).html">上一页</a>
<a href="$:(int(s)+1).html">下一页</a>
</div>

 保存到txt:

if __name__ == '__main__':
    a  = open(u'射雕**传.txt','w')
    m = 0
    for i in get_title():
        #print i[1], get_content(i[0])
        time.sleep(2)
        data = i[1] + '\n' + '\n' + get_content(i[0]).replace('</p><p>','\n\n') + '\n\n' #在标题和内容之间插入换行符,将html中的<p>参数变成换行符
        a.writelines(data)
        m += 1
        print u'正在爬取第%s段内容' % m
        # if m >2:
        #     print u'正在爬取第%s段内容' % m
        #     break
    a.close()

 

转载于:https://www.cnblogs.com/Detector/p/7604151.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值