python批量爬取小说(一步一步实现,适合新手入门)

1、下载小说的一个章节

让我们首先打开书趣阁网站中的一个小说中的一个章节,如图:
在这里插入图片描述
然后我们开始请求网页数据:

response = requests.get('http://www.shuquge.com/txt/63542/9645082.html')
# 自动解决编码问题
response.encoding = response.apparent_encoding

使用 parsel 库对数据进行解析:
解析数据一般有三种方式:正则表达式、xpath 路径提取器、css 选择器。在这里,我们使用 css 选择器。

# 将字符串内容实例化成一个对象
sel = parsel.Selector(response.text)
# ::text 是文字属性提取器
title = sel.css('.content h1::text').get()  # 可以用 #wrapper>div.book.reader>div.content>h1 代替
content = sel.css('#content::text').getall()  # 可以用 .content div.showtxt 代替

其中,::text 是文字属性提取器,sel.css() 中的内容可以用下面这种方式获得:
首先打开开发者工具,在查看器中找到小说章节的名字,然后点击鼠标右键 --> 复制 --> CSS 选择器。
在这里插入图片描述
之后,我们就可以将小说内容保存到 .txt 文件中了:

# 保存小说内容
with open(title+'.txt', mode='w', encoding='utf-8') as f:
    f.write(title+'\n')
    for i in content:
        f.write(i.strip()+'\n')

其中,.strip() 是为了去掉所有空格。

2、下载小说中的所有章节

先把之前的下载一章的代码封装成一个函数:

def download_one_chapter(url):
    response = requests.get(url)
    response.encoding = response.apparent_encoding
    sel = parsel.Selector(response.text)
    title = sel.css('.content h1::text').get()
    content = sel.css('#content::text').getall()
    with open(title+'.txt', mode='w', encoding='utf-8') as f:
        f.write(title+'\n')
        for i in content:
            f.write(i.strip()+'\n')

然后回到这个小说的目录页,用同样的方法在查看器中找到小说每一章节的下载地址的最后几位数字:
在这里插入图片描述

# 请求目录页,获取所有章节的下载地址
url = 'http://www.shuquge.com/txt/5809/index.html'
response = requests.get(url)
response.encoding = response.apparent_encoding
sel = parsel.Selector(response.text)
index = sel.css('.listmain dd a::attr(href)').getall()
for i in index[12:]:
    download_one_chapter('http://www.shuquge.com/txt/5809/'+i)

其中,index 中的内容就是这些数字,sel.css()中的内容也是按之前那种方法获取。::attr(href) 用来提取 href 中的内容。

发布了135 篇原创文章 · 获赞 30 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_36758914/article/details/105147425