这是一个练习作品。用python脚本爬取笔趣阁上面的免费小说。

环境:python3

类库:BeautifulSoup

数据源:http://www.biqukan.cc

原理就是伪装正常http请求,正常访问网页。然后通过bs4重新解析html结构来提取有效数据。

1. config文件

包含了伪装请求头部,数据源配置(如果不考虑扩展其他数据源,可以写死)。

#!/usr/bin/python

#coding:utf-8

import sys

reload(sys)

sys.setdefaultencoding('utf8')

source = {

'biquge': {

'base_url': 'http://www.biqukan.cc',

'category_min': 1,

'category_max': 2,

'category_url': 'http://www.biqukan.cc/fenlei{id}/1.html'

}

}

header = [

{'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36'},

{'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'},

{'User-Agent':'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'},

{'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1'},

{'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)'}

]

config.py文件

2. 爬取全部类目小说

#!/usr/bin/python

#coding:utf-8

import random

import requests

import re

from bs4 import BeautifulSoup

#from BeautifulSoup import BeautifulSoup

import sys

reload(sys)

sys.setdefaultencoding('utf8')

from config import source

from config import header

import hashlib

import time

hash_md5 = hashlib.md5()

##

# 通过分类获取文章名和对应的链接

#

def fiction():

url = source['biquge']['category_url']

cur_category_name = ''

_list = {}

for i in range(source['biquge']['category_min'], source['biquge']['category_max']):

req = requests.get(url.replace('{id}', '%s'%i), headers = header[random.randint(0,4)])

_temp_result = req.content.decode('gbk')

bs = BeautifulSoup(_temp_result, "html.parser")

next_page = bs.find('ul', id='pagelink')

while next_page!=None:

next_page = next_page.find('a', 'next')

if next_page==None:

break

# 更新小说

_page = _cur_page(bs)

print('page.length = %d'%len(_page))

_list.update(_page)

# 获取下一页数据

req = requests.get(next_page.attrs['href'], headers = header[random.randint(0,4)])

_temp_result = req.content.decode('gbk')

bs = BeautifulSoup(_temp_result, "html.parser")

next_page = bs.find('ul', id='pagelink')

# 短暂休息一下

time.sleep(random.random())

return _list

##

# 当前页面的所有小说信息

#

def _cur_page(bs):

_list = {}

# top列表

li_tags = bs.findAll('li', 'list-group-item')

if li_tags==None or len(li_tags)<=0:

return _list

for item in li_tags:

a_tag = item.find('a')

_item = {'name':a_tag.get_text(), 'link': a_tag.attrs['href']}

# 作者

author = item.find('small').get_text().replace('/ ', '')

_item['author'] = author

# 阅读数

readers = item.find('span').get_text()

_item['readers'] = readers

hash_md5.update(_item['link'])

_list[hash_md5.hexdigest()] = _item

# 最近更新列表

tr_tags = bs.findAll('tr')

if tr_tags==None or len(tr_tags)<=1:

return _list

for item in tr_tags:

a_tag = item.find('a')

if a_tag==None:

continue

_item = {'name':a_tag.get_text(), 'link': a_tag.attrs['href']}

# 作者

author = item.find('td', 'text-muted').get_text()

_item['author'] = author

# 状态

status = item.findAll('td')

_item['status'] = status[len(status)-1].get_text()

hash_md5.update(_item['link'])

if _list.has_key(hash_md5.hexdigest())!=True:

_list[hash_md5.hexdigest()] = _item

else:

_list[hash_md5.hexdigest()]['status'] = _item['status']

return _list

if __name__=="__main__":

_temp = fiction()

print('done')

fiction.py文件

3. 爬取小说介绍信息

#!/usr/bin/python

#coding:utf-8

import random

import requests

import re

from bs4 import BeautifulSoup

#from BeautifulSoup import BeautifulSoup

import sys

reload(sys)

sys.setdefaultencoding('utf8')

from config import source

from config import header

##

# 抓取简介,返回结构体

# 标题:知否?知否?应是绿肥红瘦

# 作者:关心则乱

# 分类:都市言情

# 字数:200万

# 阅读数:2w+

# 状态:连载中、完结

# 封面:url

# 简介:赵丽颖、冯绍峰主演电视剧《知否?知否?应是绿肥红瘦》原著,该剧由正午阳光影业出品,侯鸿亮任制片人,2017年9月6日开机。宅斗翘楚、古言大神关心则乱,手把手传授你实用的古代生存指南。一个消极怠工的古代庶女,生活如此艰难,何必卖力奋斗。古代贵族女子的人生基调是由家族决定的,还流行株连,一个飞来横祸就会彻底遭殃,要活好活顺活出尊严,明兰表示,鸭梨很大。古代太危险了,咱们还是睡死算了。

#

def summary(url):

_result={'title':'', 'author':'', 'category':'', 'words':'', 'readers':'', 'status':'', 'cover_img':'', 'summary':''}

req = requests.get(url,headers = header[random.randint(0,4)])

_temp_result = req.content.decode('gbk')

bs = BeautifulSoup(_temp_result, "html.parser")

title_tag = bs.find('h1', 'bookTitle')

if title_tag!=None:

_result['title'] = title_tag.get_text()

book_tag = bs.find('p', 'booktag')

if book_tag!=None:

a_tags = book_tag.findAll('a')

_result['author'] = a_tags[0].get_text()

_result['category'] = a_tags[1].get_text()

span_tags = book_tag.findAll('span')

_result['words'] = span_tags[0].get_text()

_result['readers'] = span_tags[1].get_text()

_result['status'] = span_tags[2].get_text()

intro_tag = bs.find('p', id='bookIntro')

_result['cover_img'] = intro_tag.find('img').attrs['src']

_result['summary'] = intro_tag.get_text().replace('\n\r\n ','').replace('\r\n ','')

return _result

if __name__=="__main__":

_temp = summary('http://www.biqukan.cc/book/47583/')

print(_temp)

summary.py文件

4. 爬取小说目录

#!/usr/bin/python

#coding:utf-8

import random

import requests

import re

from bs4 import BeautifulSoup

#from BeautifulSoup import BeautifulSoup

import sys

reload(sys)

sys.setdefaultencoding('utf8')

from config import source

from config import header

# 抓取目录

def catalog(url):

_list=[]

req = requests.get(url,headers = header[random.randint(0,4)])

_temp_result = req.content.decode('gbk')

bs = BeautifulSoup(_temp_result, "html.parser")

all_list = bs.find('div', id='list-chapterAll')

if all_list==None:

return _list

list_tag = all_list.find('dl', 'panel-chapterlist')

if list_tag==None:

return _list

a_tags = list_tag.findAll('a')

for k in a_tags:

_dict={}

_dict['name'] = k.get_text()

_dict['link'] = url + k.attrs['href']

_list.append(_dict)

return _list

if __name__=="__main__":

_temp = catalog('http://www.biqukan.cc/book/47583/')

print(_temp)

catalog.py文件

5. 爬取小说正文

#!/usr/bin/python

#coding:utf-8

import random

import requests

import re

from bs4 import BeautifulSoup

#from BeautifulSoup import BeautifulSoup

import sys

reload(sys)

sys.setdefaultencoding('utf8')

from config import source

from config import header

##

# 抓取小说正文

#

def detail(url):

per_artitle_limit_page = 3;

title=''

content=''

for i in range(1, per_artitle_limit_page):

if i==1:

part_url = ''

else:

part_url = '_%s'%i

req = requests.get(url.replace('.html',part_url + '.html'),headers = header[random.randint(0,4)])

_temp_result = req.content.decode('gbk')

bs = BeautifulSoup(_temp_result, "html.parser")

# title

if len(title)<=0:

title = bs.find('li','active').get_text()#re.findall(title_re, _temp_result)[0]

content_tag = bs.find('div', id='htmlContent')

if content_tag==None:

break

next_tag = content_tag.find('p', 'text-danger')

if next_tag!=None:

next_tag.clear()

_ = content_tag.get_text().replace('-->>', '').replace('一秒记住【笔趣阁 www.biqukan.cc】,更新快,无弹窗,免费读!','')

content += _

return content

def filter(content):

_temp = content.split('\r\n')

for index in range(len(_temp)):

_temp[index] = _temp[index].replace(' ','')

_temp = [elem for elem in _temp if elem != None and len(elem) != 0]

return ''.join(_temp)

if __name__=="__main__":

_temp = detail('http://www.biqukan.cc/book/20461/12592815.html')

print(filter(_temp))

article.py文件

总结

暂没有做数据保存模块。如果需要串起来做成一个完整的项目的话,只需要把小说数据结构保存即可(节省磁盘空间)。通过小说url可以很快速的提取出小说简介、目录、每一章的正文。

如果想要做的更好,可以把目录,介绍、正文等部分缓存起来,当然得有足够的空间。

python爬取小说写入txt_Python BeautifulSoup 爬取笔趣阁所有的小说相关推荐

  1. 2021年scrapy一分钟内爬取笔趣阁整本小说存为txt|解决章节排序问题

    本人是一个小说迷,喜欢用电纸书看小说,但苦于难以寻找网络小说的txt版本,加之最近学习了一下怎么用scrapy爬取网页数据,所以想到去使用scrapy框架来爬取笔趣阁小说存为txt文件,在爬取过程中对 ...

  2. python爬取小说写入txt_Python爬虫爬取小说,并保存至本地文本文件中

    运行环境:Python3.6.Pycharm2017.3.Windows10 RS3.requests2.18.4.BeautifulSoup4.6.0 简介 运行效果展示 ① book136_sin ...

  3. Python爬虫(scrapy模块、bs4模块) 爬取笔趣阁全本小说(三级页面)

    今天要做的是一个爬虫小项目,爬取小说网站,那么首先呢先对网站进行分析,这里要想爬取到每部小说的全部章节,需要爬取到三级页面,让我们看看代码实现.(https://m.wanwenhui.com/shu ...

  4. java爬取笔趣阁魔道祖师小说

    @RequestMapping("biquge")@ResponseBodypublic void biquge() throws Exception {int i=1;Strin ...

  5. python爬取小说写入txt_对新笔趣阁小说进行爬取,保存和下载!这就是Python的魅力...

    原标题:对新笔趣阁小说进行爬取,保存和下载!这就是Python的魅力 以前挺爱在笔趣阁看小说的(老白嫖怪了) 现在学了一点爬虫技术,就自然而然的想到了爬取笔趣阁的小说 也算锻炼一下自己的技术,就以新笔 ...

  6. Python爬虫练习(一) 爬取新笔趣阁小说(搜索+爬取)

    爬取笔趣阁小说(搜索+爬取) 首先看看最终效果(gif): 实现步骤: 1.探查网站"http://www.xbiquge.la/",看看网站的实现原理. 2.编写搜索功能(获取每 ...

  7. Python 爬虫复习之爬取笔趣阁小说网站(不用正则)

    前言 小说网站-笔趣阁:URL:https://www.qu.la/ 笔趣阁是一个盗版小说网站,这里有很多起点中文网的小说,该网站小说的更新速度稍滞后于起点中文网正版小说的更新速度.并且该网站只支持在 ...

  8. 1.python爬取笔趣阁小说

    前一阵无聊想学习python,就有了以下代码,选取了笔趣阁这个大众化的网站,百度发现以笔趣阁为名的小说网站很多,本段代码只在百度结果里选取前五条,并选取了三个叫笔趣阁的网站,前五条里包含笔趣阁的任意一 ...

  9. Python爬虫爬取笔趣阁小说

    笔趣阁链接 编码转换链接 目前只做了在线阅读部分,其他部分由于时间原因没有写,有兴趣的可以自己补充. #引入模块 import urllib.request,re,urllib,requests fr ...

最新文章

  1. html 跨域_常见跨域解决方案以及Ocelot 跨域配置
  2. 在Windows下为PHP安装redis扩展
  3. LevelDB 源码剖析(六)WAL模块:LOG 结构、读写流程、崩溃恢复
  4. 汇编语言 利用ASCII以及AND OR进行字符串大小写转换
  5. 你是在用计算机算你的人生经历吗,计算机人生规划
  6. 无线模块的电源设计指南
  7. html 类型转换,JavaScript怎么进行类型转换?
  8. 数字化时代的新职业教育行业洞察
  9. 《BackTrack 5 Cookbook中文版——渗透测试实用技巧荟萃》—第1章1.3节安装BackTrack到USB驱动器...
  10. ZeroMQ接口函数之 :zmq_tcp – 使用TCP协议的ØMQ网络单播协议
  11. comet学习(三)cometd心跳机制
  12. 关于无线温度监测系统
  13. 分析力学-清华大学基科班课件
  14. python存储-Python数据存储之 h5py详解
  15. 多客技巧分享|【建议收藏】TikTok七大避坑指南帮你少走许多弯路
  16. 保护眼睛的屏幕设置 Win2008R2中的Win7桌面效果设置
  17. 原始的ajaxtookit的使用
  18. 从 http 升级到 https 过程中遇到的一些问题
  19. 2008北京地铁线路图
  20. CNC控制板和步进电机驱动器的连接方法

热门文章

  1. php composer源码打包,手把手教你发布自己的 Composer 包
  2. 唤起你对c#曾经的记忆
  3. 多目标遗传算法与优化的关系
  4. 实现让两个DIV横向排列方法揭秘
  5. 统计各部门的薪水总和_近年来,统计学热过金融火过计算机,这是真的吗?
  6. matlab输出lccde_Matlab与Visual C++混合编程处理全站仪数据的方法
  7. pymysql使用变化的变量,构造SQL语句
  8. linux+广播程序,Linux系统下广播程序制作介绍(上) (3)
  9. linux各版本基线检查脚本(centos6、centos7、ubuntu系列)
  10. 系统部署时的Could not load file or assembly 'Microsoft.VisualStudio.Enterprise.ASPNetHelper问题...