Python超简单超基础的免费小说爬虫!爬虫入门从这开始!

209 阅读2分钟

需要准备的环境

1.python 3.0及以上皆可
2.requests库,os,re

选取网页

找一个免费的小说网站,我在这里拿www.zanghaihua.org/wanlishiwun… 来举例子

思路

PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取

python免费学习资料以及群交流解答点击即可加入

1.首先来看看网页的结构
右键网页,点击“查看网页源代码”

![](https://p6-tt-ipv6.byteimg.com/origin/pgc-image/ea1e76ed87234e889de6926e984f447f)

不难发现看到章节链接的格式都是 章节名称

![](https://p1-tt-ipv6.byteimg.com/origin/pgc-image/478fa789a16b42bcbbc728b75b8ff8b2)

随便点开一个章节,进入小说内容页面,然后再去看看源代码

![](https://p1-tt-ipv6.byteimg.com/origin/pgc-image/0510580496ce4a3d90979897128c0a20)

还是不难发现文本的结构是

内容

<div

我们可以把爬取每个章节链接存到一个列表里面,再让python再次访问这个链接去爬取内容,最后写入文档,接下来直接上代码,注释我都写好了。

”我看你就是讲不懂才直接上代码的“
闭嘴[滑稽]

代码

#导入库
import requests
import os
import re

#定义请求协议头
headers = {

'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'referer': 'http://www.zanghaihua.org/wanlishiwunian/',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3776.400 QQBrowser/10.6.4212.400',
}

mulu_url = 'http://www.zanghaihua.org/wanlishiwunian/'#目录网址
html = requests.get(mulu_url,headers=headers)#目录源代码
html.encoding = 'utf-8'#文字兼容
psgurl_list = []#创建章节网址列表
psgname_list = []#创建章节名称列表
psg_urls =re.findall('</span><span> <a href="(.*?)">.*?</a>',html.text)#获得每个章节的网址
psg_names = re.findall('</span><span> <a href=".*?">(.*?)</a>',html.text)#获得每个章节的名称
#通过for循环每次搜索一到一个加入一个到列表
for psg_urls in psg_urls:
    psgurl_list.append(psg_urls)
book = open('万历十五年.txt',mode='w')#提前打开文本文档
for i in range(1,46):#这里1和46是章节数,应该有更好的方法,但是我就会这个QAQ
    i+1
    mymes_html = requests.get(psgurl_list[i],headers=headers)
    mes_names = psg_names[i]
#爬出来是乱码,我们让文字兼容一下
    mymes_html.encoding = 'utf-8'
    mes_html = mymes_html.text

#过滤一下符号英文字母以及分段
    mes_br = re.findall('<div class="bookcontent clearfix" id="BookText">(.*?)<br/><br/><div',mes_html)#爬取内容
    str1 = ' '.join(mes_br )#列表转字符串
    mes = re.sub('<br/><br/>',' ',str1)#过滤爬出来文本中的杂乱符号
    allmes =  mes_names+ '\n' + mes#每段加入文章名

    #写入工作

    book.write(allmes+'\n')#写入
book.close()#关闭文本文档

最后在py文件同一目录下出现了一个文本文档,点开

![](https://p26-tt.byteimg.com/origin/pgc-image/7e5c801b0e0a42cb907bb407fb1e6f69)

成功了

总结

此爬虫是受Macro大佬的微博图片爬虫受启发写出来的。

这种方法只适合一些小网站,收费的网站需要js解析等等,作为萌新这点就够练了。
萌新的第一个博客,代码上面可能有点不简洁,有什么建议可以提出来,不喜勿喷。

最后祝各位万事成功!Go fot it!