再写一个用BeautifulSoup抓站的工具,体会BeautifulSoup的强大。

根据小说索引页获取小说全部章节内容并在本地整合为小说全文。不过不是智能的,不同的站点对代码需要做相应的修改。

#!/usr/bin/env python

import os
import sys
import re
import time
import chardet
import urllib.request as ur
from urllib.parse import urljoin,urlparse
from bs4 import BeautifulSoup
from threading import Thread class Download(Thread): #为每个章节分配多线程
def __init__(self,filepath,info):
Thread.__init__(self)
self.filepath = filepath
(self.link,self.chapter) = info def run(self):
print('开始下载: '+self.chapter)
section(self.filepath,self.chapter,self.link)
print('完成下载: '+self.chapter) def getData(url): #主要用于判断页面编码,但是发现BeautifulSoup自带判定能力,故废弃此函数
charsets = 'utf8'
response = ur.urlopen(url,timeout = 10)
html = response.read()
charinfo = chardet.detect(html)
charsets = charinfo['encoding']
data = html.decode(charsets)
return data def merge(tmpFiles,targetFile): #将下载的章节合并
for tmpFile in tmpFiles:
with open(targetFile,'a+') as wfile:
wfile.write(open(tmpFile,'r').read())
os.remove(tmpFile) def content(link): #获取章节页面的小说内容。对于不同的站点,在此函数内修改获取章节内容的代码
html = ur.urlopen(link,timeout = 10)
soup =BeautifulSoup(html)
contents = soup.find(id = 'readtext').p.span.text.replace('  ','\n') #BeautifulSoup会自动将&nbsp;转换为空格,<br/>转换为特殊符号
return contents def section(filepath,chapter,link): #下载章节内容
while True: #反复请求页面
try:
with open(filepath,'w') as nfile:
nfile.write(chapter+'\n'+content(link)+'\n')
break
except:
pass def index(url): #获取章节索引
indexs = []
while True: #反复请求页面
try:
html = ur.urlopen(url,timeout = 10)
#html = html.read().decode('gb2312')
#html = getData(url)
soup = BeautifulSoup(html,from_encoding = 'gbk')#BeautifulSoup能自动识别编码,但是会将gbk页面识别为gb2312页面,可能导致页面内部分数据获取失败,故显式指定
break
except:
pass
title = soup.find(name = 'div',attrs = {'class':'booktext'}).text
indexDiv = soup.find(name = 'div',attrs = {'class':'booktext'})
indexUl = [ul for ul in indexDiv.find_all('ul') if ul][1:]
for ul in indexUl:
indexList = [li.a for li in ul.find_all('li') if li]
index = [(urljoin(url,a.get('href')),a.text) for a in indexList if a]
indexs +=index
return indexs def novel(url):
tmpFiles = []
tasks = []
try:
indexs = index(url)
tmpDir = os.path.join(os.getcwd(),'tmp')
if not os.path.exists(tmpDir): #创建章节片段存放的临时目录
os.mkdir(tmpDir)
for i,info in enumerate(indexs):
tmpFile = os.path.join(tmpDir,str(i))
tmpFiles.append(tmpFile)
task = Download(tmpFile,info) #开启新线程下载章节内容
task.setDaemon(True)
task.start()
tasks.append(task)
if len(tasks) >= 20: #将线程总数控制在20个以内,如果线程过多会导致程序崩溃
while len([task for task in tasks if task.isAlive()]):
print( '进度: {} / {}'.format(i+1-len([task for task in tasks if task.isAlive()]),len(indexs))) #显示下载进度
time.sleep(2)
tasks = []
if i == len(indexs) - 1:
while len([task for task in tasks if task.isAlive()]):
print( '进度: {} / {}'.format(len(indexs) - len([task for task in tasks if task.isAlive()]),len(indexs)))
time.sleep(2)
print( '进度: {} / {}'.format(len(indexs),len(indexs)))
print('开始整合......')
merge(tmpFiles,os.path.join(os.getcwd(),title+'.txt'))
print('下载成功!')
except Exception as ex:
print(ex)
print('下载失败!')
sys.exit()
def main(argv):
try:
novel(argv[0])
except KeyboardInterrupt as kbi: #使用<C-c>中断下载后仍然能将已下载的章节合并
tmpDir = os.path.join(os.getcwd(),'tmp')
if os.path.exists(tmpDir):
tmpFiles = [os.path.join(tmpDir,tfile) for tfile in os.listdir(tmpDir) if os.path.isfile(os.path.join(tmpDir,tfile))]
print('开始整合不完整的下载......')
try:
merge(tmpFiles,os.path.join(os.getcwd(),'不完整文档.txt'))
if os.path.exists(os.path.join(os.getcwd(),'不完整文档.txt')):
print('部分章节下载成功!')
else:
print('下载失败!')
except:
print('下载失败!')
sys.exit()
os.rmdir(tmpDir)
else:
print('下载失败!')
sys.exit()
if os.path.exists(os.path.join(os.getcwd(),'tmp')):
os.rmdir(os.path.join(os.getcwd(),'tmp')) if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1:])
#http://www.lueqiu.com/

截图:

Python3利用BeautifulSoup4抓取站点小说全文的代码的更多相关文章

  1. python3.4学习笔记(十七) 网络爬虫使用Beautifulsoup4抓取内容

    python3.4学习笔记(十七) 网络爬虫使用Beautifulsoup4抓取内容 Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖 ...

  2. 对比使用Charles和Fiddler两个工具及利用Charles抓取https数据(App)

    对比使用Charles和Fiddler两个工具及利用Charles抓取https数据(App) 实验目的:对比使用Charles和Fiddler两个工具 实验对象:车易通App,易销通App 实验结果 ...

  3. 利用Crowbar抓取网页异步加载的内容 [Python俱乐部]

    利用Crowbar抓取网页异步加载的内容 [Python俱乐部] 利用Crowbar抓取网页异步加载的内容 在做 Web 信息提取.数据挖掘的过程中,一个关键步骤就是网页源代码的获取.但是出于各种原因 ...

  4. 利用Fiddler抓取websocket包

    一.利用fiddler抓取websockt包 打开Fiddler,点开菜单栏的Rules,选择Customize Rules... 这时会打开CustomRules.js文件,在class Handl ...

  5. Python3.x:抓取百事糗科段子

    Python3.x:抓取百事糗科段子 实现代码: #Python3.6 获取糗事百科的段子 import urllib.request #导入各类要用到的包 import urllib import ...

  6. Python爬虫实战八之利用Selenium抓取淘宝匿名旺旺

    更新 其实本文的初衷是为了获取淘宝的非匿名旺旺,在淘宝详情页的最下方有相关评论,含有非匿名旺旺号,快一年了淘宝都没有修复这个. 可就在今天,淘宝把所有的账号设置成了匿名显示,SO,获取非匿名旺旺号已经 ...

  7. 利用wireshark抓取远程linux上的数据包

    原文发表在我的博客主页,转载请注明出处. 前言 因为出差,前后准备总结了一周多,所以博客有所搁置.出差真是累人的活计,不过确实可以学习到很多东西,跟着老板学习做人,学习交流的技巧.入正题~ wires ...

  8. 利用wget 抓取 网站网页 包括css背景图片

    利用wget 抓取 网站网页 包括css背景图片 wget是一款非常优秀的http/ftp下载工具,它功能强大,而且几乎所有的unix系统上都有.不过用它来dump比较现代的网站会有一个问题:不支持c ...

  9. Python3利用BeautifulSoup4批量抓取站点图片的代码

    边学边写代码,记录下来.这段代码用于批量抓取主站下所有子网页中符合特定尺寸要求的的图片文件,支持中断. 原理很简单:使用BeautifulSoup4分析网页,获取网页<a/>和<im ...

随机推荐

  1. Delete Exists

    Create PROCEDURE [dbo].[LVS_Update_WaferInfo] @LotId varchar(40), @xmlData xmlasBEGIN delete W from ...

  2. 基于MFC的单文档,多文档,对话框应用程序

    从类的角度区分: 基于对话框(3个类): CAboutDlg 程序名App 程序名Dlg 单文档(5个类): CAboutDlg CMainFrame 程序名App 程序名Doc 程序名View 多文 ...

  3. 【原创】android内存管理-hprof文件

    转载请注明出处 http://www.cnblogs.com/weiwangnuanyang/p/5703702.html 如果只是想确定一下某一个场景是否有内存泄漏,AndroidStadio的控制 ...

  4. OC编程的一些UI细节

    1/如果你想用一个半透明的View遮住当前窗口,连并NavigationBar也一并遮住的话,那么你需要 将视图添加到navigationController的View上 [self.navigati ...

  5. Ninject之旅之二:开始使用Ninject(附程序下载)

    摘要 这篇文章介绍怎样将Ninject添加到实际的项目中,使用Ninject框架最基本的功能.首先用一个Hello World例子介绍怎么添加和使用Ninject.然后用一个更复杂的例子,介绍Ninj ...

  6. 通过DIV+span方式模拟进度条的实现方法

    上上周用FusionCharts做报表时,有个图是进度条的形式,其实在FusionCharts 3.0之后已经支持了(Linear Gauge),可惜现有系统用的还是1.2.3版本的,重新引入新版本有 ...

  7. iOS视频播放器

    用AVPlayer写的一个简单的播放器,支持横竖屏旋转! https://github.com/shumingli/module 欢迎加iOS开发交流群:516318591

  8. wamp 配置遇到的问题

    /* 最近开发部署更换到国内的服务器,想来想去还是更换为wamp套件. 但是由于下的版本的都不太适合. 外网一直显示拒绝.排查问题之后 写个笔记做个记录 */ wamp You don't have ...

  9. Linq的一些很方便的方法

    Aggregate Aggregate我用的最多的地方就是拼接字符串,打个比方来说,如果有数组,想要的结果是在他们之间插入一个","然后返回拼接以后的新字符串. 常规的做法是: L ...

  10. bindActionCreators

    在 http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html 没有介绍这个,react-red ...