通过python 爬虫 爬取小说
使用python版本为3.6
模块为 Requests,BeautifulSoup
通过此次爬取小说 来练习 Requests及BeautifulSoup 模块用法
小说url=‘http://www.23us.com/html/63/63392/’
第一步 通过 Requests 来获取到网页源代码
url = "http://www.23us.com/html/63/63392/"
reObj = requests.get(url)
我们运行测试一下

Response[200]说明 成功
接下来 使用Beautifulsoup 来获取网页源代码
bsObj = BeautifulSoup(reObj.text,'html.parser')
print(bsObj)

运行发现 网页源代码成功获取得到,但编码有问题,所以我们需要改变编码。
可以使用reObj.encoding 来获取网页的编码格式

然后修改代码
url ='http://www.23us.com/html/63/63392/25724970.html'
reObj = requests.get(url)
html = reObj.text.encode('ISO-8859-1').decode('gbk')
bsObj = BeautifulSoup(html,'html.parser')
print (bsObj)
运行试一试效果

中文已经可以显示出来。
接下来,我们就需要对源码进行筛选,筛选出我们需要的东西
章节名以及章节链接
右键审查元素 找到所需要的章节目录的代码

查看发现小说章节目录都存放在 td 列表标签内。
所以可以通过BeautifulSoup的find_all方法来找到td标签
代码如下:
for data in bsObj.find_all('td'):
if (data.a) !=None :
url_list += [(data.a.get('href'))]
为什么要用 if 来判断呢? 因为我发现由于在最后面有两个 td 标签中并没有我们想要的数据
在遍历的过程中会出现None 导致程序错误,所以我使用了一个if 来判断是否为空值
url_list 是一个列表 用来存放 找到的 章节链接

那么接下来就应该要开始获取各个章节的内容了。而发现url_list 中的url 并不是一个完整的url链接,所以我们需要通过字符串拼接之后再获取各个章节的页面。同样,我们需要改变编码和解码方式,使显示正确。
for item in url_list:
tabel_url = (url +item)
reObj_ta = requests.get(tabel_url)
html_ta = reObj_ta.text.encode('ISO-8859-1').decode('gbk')
bsObj_ta = BeautifulSoup(html_ta,'html.parser')
遍历 url_list 字符串拼接上url 然后通过requests BeautifulSoup 获取网页源代码
离成功只有最后一步了,继续右键审查元素,找到章节名和文章的标签,筛选出来就可以了。


相应筛选标签的代码
article = bsObj_ta.find_all('dd',id="contents")
for content in article:
content.get_text()
title = bsObj_ta.find('h1').get_text()
运行后获取到的内容

可以发现正文部分还是有一些标签存在,这里我使用的是操作字符串的strip 以及replace来进行数据清洗


最后再将所爬取的小说内容,存放到txt中,方便阅读
with open ("G:/yinianyongheng.txt",'a',encoding='utf-8') as f:
f.write(title + '\n')
f.write(content +'\n')
完整代码截图

网友评论