Python3网络爬虫:使用Beautiful Soup爬取小说
本文是http://blog.csdn.net/c406495762/article/details/71158264的学习笔记
作者:Jack-Cui
博主链接:http://blog.csdn.net/c406495762
运行平台: OSX
Python版本: Python3.x
IDE: pycharm
一、Beautiful Soup简介
简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:
Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。
Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。
二、Beautiful Soup学习
在这里推荐 Python爬虫利器二之Beautiful Soup的用法 ,和官方文档相似,但是内容作了精简.
另附上 官方文档 的链接
三、实战
小说网站-笔趣看:
URL:http://www.biqukan.com/
以该小说网为例,爬取《神墓》
整体思路:
1. 选择神墓小说某一章节,检查,找到正文部分的TAG
2. 尝试使用BeautifulSoup打印出该章节正文部分内容
3. 从索引爬取全部的章节的url,用for循环打印
4. 结合3、2并将2的打印部分换成写入文件
具体步骤:
1. 选择《神墓》小说第一章,检查,找到正文部分的html标签
链接url:http://www.biqukan.com/3_3039/1351331.html
发现小说正文部分所在标签是:
<div id='content' class='showtxt'>正文部分</div>
2. 尝试使用BeautifulSoup打印出该章节正文部分内容
from urllib import request
from bs4 import BeautifulSoup
import os
def download_specified_chapter(chapter_url,header,coding,chapter_name=None):#先生成一个request对象,传入url和headersdownload_req = request.Request(chapter_url,headers=header)#通过指定urlopen打开request对象中的url网址,并获得对应内容response = request.urlopen(download_req)#获取页面的htmldownload_html = response.read().decode(coding, 'ignore')#获取html的bsorigin_soup = BeautifulSoup(download_html, 'lxml')#获取小说正文部分content=origin_soup.find(id='content', class_='showtxt')#经打印,发现文本中有众多的\xa0(在html中是 ),并且没有换行,print(repr(content.text))#整理小说格式,将\xa0替换成回车# html中的 ,在转换成文档后,变成\xa0txt=content.text.replace('\xa0'*8,'\n')print(txt)
if __name__=="__main__":target_url='http://www.biqukan.com/3_3039/1351331.html'header = {'User-Agent':'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/''535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'}download_specified_chapter(target_url,header,'gbk')
结果如图:
3. 从索引爬取全部的章节的url,用for循环打印
索引的url:http://www.biqukan.com/3_3039/
检查后发现
我们所需要的章节的url,在<div class="lsitmain">
下的<dl>
下的<dd>
中的<a>
标签中,并且是在<dt>《神墓》正文卷</dt>
之后.
尝试用for循环打印:
from urllib import request
from bs4 import BeautifulSoupif __name__ == "__main__":index_url = "http://www.biqukan.com/3_3039/"header={'User-Agent': 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/''535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'}#指定url,header生成requesturl_req = request.Request(index_url,headers=header)#打开url,并获得请求内容responseresponse = request.urlopen(url_req)#读取response的内容,用gbk解码,得到html内容html = response.read().decode('gbk', 'ignore')#用BeautifulSoup处理得到的网页htmlhtml_soup = BeautifulSoup(html,'lxml')# index = BeautifulSoup(str(html_soup.find_all('div', class_='listmain')),'lxml')# print(html_soup.find_all(['dd', ['dt']]))#判断是否找到了《神墓》正文卷body_flag = False for element in html_soup.find_all(['dd', ['dt']]):if element.string == '《神墓》正文卷':body_flag = Trueif body_flag is True and element.name == 'dd':chapter_name = element.stringchapter_url = "http://www.biqukan.com"+element.a.get('href')print(" {} 链接:{}".format(chapter_name,chapter_url))
执行结果:
4.结合3、2并将2的打印部分换成写入文件
由步骤3 获得章节的url,再由步骤2 根据url,获得正文部分,两相结合,再不断地将内容写入文件中.
代码如下:
from urllib import request
from bs4 import BeautifulSoupdef download_specified_chapter(chapter_url, header, coding, chapter_name=None):#先生成一个request对象,传入url和headersdownload_req = request.Request(chapter_url,headers=header)#通过指定urlopen打开request对象中的url网址,并获得对应内容response = request.urlopen(download_req)#获取页面的htmldownload_html = response.read().decode(coding, 'ignore')#获取html的bsorigin_soup = BeautifulSoup(download_html, 'lxml')#获取小说正文部分content=origin_soup.find(id='content', class_='showtxt')#整理小说格式,将\xa0替换成回车# html中的 ,在转换成文档后,变成\xa0txt=content.text.replace('\xa0'*8,'\n')# 将获得的正文 写入txtprint("正在下载 {} 链接:{}".format(chapter_name,chapter_url))with open('《神墓》.txt','a') as f:if chapter_name is None:f.write('\n')else :f.write('\n'+chapter_name+'\n')f.write(txt)
if __name__ == "__main__":index_url = "http://www.biqukan.com/3_3039/"header={'User-Agent': 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/''535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'}#指定url,header生成requesturl_req = request.Request(index_url,headers=header)#打开url,并获得请求内容responseresponse = request.urlopen(url_req)#读取response的内容,用gbk解码,得到html内容html = response.read().decode('gbk', 'ignore')#用BeautifulSoup处理得到的网页htmlhtml_soup = BeautifulSoup(html,'lxml')# index = BeautifulSoup(str(html_soup.find_all('div', class_='listmain')),'lxml')# print(html_soup.find_all(['dd', ['dt']]))#判断是否找到了《神墓》正文卷body_flag = Falsefor element in html_soup.find_all(['dd', ['dt']]):if element.string == '《神墓》正文卷':body_flag = True#从《神墓》正文卷 之后的dd就是顺序的章节目录if body_flag is True and element.name == 'dd':chapter_name = element.stringchapter_url = "http://www.biqukan.com"+element.a.get('href')download_specified_chapter(chapter_url, header, 'gbk', chapter_name)
结果如图:
txt截图:
这样就大功告成 ^_^
Python3网络爬虫:使用Beautiful Soup爬取小说相关推荐
- Python手记-10:Beautiful Soup爬取豆瓣经典书单
目录 1. Beautiful Soup简介 2. Beautiful Soup简单使用 2.1 对象种类 2.2 遍历文档树 2.2.1 子节点 2.2.2 父节点 2.2.3 兄弟节点 2.2. ...
- python爬去百度百科词条_Python爬虫入门学习实践——爬取小说
本学期开始接触python,python是一种面向对象的.解释型的.通用的.开源的脚本编程语言,我觉得python最大的优点就是简单易用,学习起来比较上手,对代码格式的要求没有那么严格,这种风格使得我 ...
- Python3写爬虫(五)爬取糗事百科段子
2019独角兽企业重金招聘Python工程师标准>>> 最近几天开始用Python3改写网上用Python2写的案例,发现完全可以用Python3来重构Python2的源码.本篇文章 ...
- Java网络爬虫(三)爬取网络小说
因CSDN版权问题,小说网站的URL.图片不可在此公布,读者根据自己想要爬取的网站,自行选择网站即可. 1.爬取小说章节内容,需要注意的大部分原创小说内容页是禁用右键的,无法直接选取页面内容进行元素检 ...
- python爬虫实例之——多线程爬取小说
之前写过一篇爬取小说的博客,但是单线程爬取速度太慢了,之前爬取一部小说花了700多秒,1秒两章的速度有点让人难以接受. 所以弄了个多线程的爬虫. 这次的思路和之前的不一样,之前是一章一章的爬,每爬一章 ...
- 【零基础学爬虫】用python爬取小说
文章目录 前言 一.先上效果图 二.bs4学习 1.原理 2.运用 3.数据解析 4.属性定位 5. 获取标签之间的文本数据 6.获取标签中的属性值 三.开始爬小说 一般步骤 1.获取url 2 .U ...
- python 小说爬虫_Python实现的爬取小说爬虫功能示例
本文实例讲述了Python实现的爬取小说爬虫功能.分享给大家供大家参考,具体如下: 想把顶点小说网上的一篇持续更新的小说下下来,就写了一个简单的爬虫,可以爬取爬取各个章节的内容,保存到txt文档中,支 ...
- Python3网络爬虫:我要爬帅哥!!!(爬取帅哥图)
转载请注明作者和出处: https://blog.csdn.net/qq_45627785?spm=1011.2124.3001.5343 运行平台:Windows Python版本:Python 3 ...
- 详解Python 采用 requests + Beautiful Soup 爬取房天下新楼盘推荐
最近一直在关注Python写爬虫相关的知识,尝试了采用requests + Beautiful Soup来爬取房天下(原搜房网)的推荐新楼盘. 不用不知道,一用发现有惊喜也有惊吓,本文就一同记录下惊喜 ...
最新文章
- 深度介绍分布式系统原理与设计
- Swift之深入解析可选类型Optional的底层原理
- SegmentFault Hackathon 文艺复兴
- html怎么把excel表格合并单元格,Excel中如何快速合并多个单元格
- usb接口供电不足_主板接口不认识?一分钟带你了解电脑主板接口
- 面试题13. 机器人的运动范围
- 软件测试英语笔试,软件测试英文面试笔试题
- 在linux vi中激活鼠标中键,实现滚动换行
- BZOJ3224 Tyvj 1728 普通平衡树
- mysql 修改root密码 修改账户登录host
- 留言板php数据库_php实现留言板功能(连接数据库)的实例讲解
- 比PS更简单好用的自动抠图软件 一键抠图工具
- 01_配置yum源-银河麒麟V10(Kylin Linux Advanced Server V10 (Tercel))操作系统
- 什么是指令集架构ISA【从处理器谈起】
- 编译程序和解释程序的区别
- 专访李亚锋:“大数据+”趋势下的电信实践之路
- Spark中资源与任务的关系
- arcgis中字段的融合_利用ArcGis进行地理处理之三(融合)
- 【paper 学习】1、DeepWiFi: Cognitive WiFi with Deep Learning
- train_test_split参数含义