Python爬虫从入门到精通:(7)数据解析3_使用bs4爬取《红楼梦》小说_Python涛哥

45 篇文章 18 订阅

爬取红楼梦全篇内容:

在这里插入图片描述


数据解析步骤:章节标题,详情页url,章节内容
在这里插入图片描述

通过浏览器开发者工具中,我们得知。小说章节的标题,和每一张的链接,都在<li>标签中。


现在我们用bs4把这2个数据提取出来。

import requests
from bs4 import BeautifulSoup

main_url = 'https://www.shicimingju.com/book/hongloumeng.html'
reponse = requests.get(url=main_url)
reponse.encoding = 'utf-8'
page_text = reponse.text
soup = BeautifulSoup(page_text, 'lxml')

定位到了<li>标签,最好用层级标签:

a_list = soup.select('.book-mulu > ul > li')

章节标题:定位到的所有的符合要求的a标签

title = a.string

每个章节点进去看的地址:
在这里插入图片描述

detail_url = 'https://www.shicimingju.com/' +a.a['href']

对详情页发起请求解析出章节内容:

reponse = requests.get(url=detail_url, headers=headers)
reponse.encoding = 'utf-8'
page_text_detail = reponse.text

在这里插入图片描述

分析后,我们可以看到,小说的篇幅内容都在<div class="card bookmark-list"> 内。通过属性定位,我们可以取到数据:

div_tag = soup.find('div', class_="chapter_content")
content = div_tag.text

最后,我们需要保存下数据。

完整代码如下:

# 爬取红楼梦全篇内容:
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36'
}
main_url = 'https://www.shicimingju.com/book/hongloumeng.html'
reponse = requests.get(url=main_url)
reponse.encoding = 'utf-8'
page_text = reponse.text
print(page_text)

# 存储
f = open('hongloumeng.txt', 'a+', encoding='utf-8')

soup = BeautifulSoup(page_text, 'lxml')
a_list = soup.select('.book-mulu > ul > li')
for a in a_list:
    title = a.string
    detail_url = 'https://www.shicimingju.com/' + a.a['href']
    # 对详情页发起请求解析出章节内容
    reponse = requests.get(url=detail_url, headers=headers)
    reponse.encoding = 'utf-8'
    page_text_detail = reponse.text
    soup = BeautifulSoup(page_text_detail, 'lxml')

    div_tag = soup.find('div', class_="chapter_content")
    content = div_tag.text
    f.write(title + ':' + content + '\n')
    print(title, '保存成功!!!')
f.close()

等待爬取完毕后,我们就看到了整篇内容!
在这里插入图片描述
在这里插入图片描述

关注 Python涛哥,学习更多Python知识!

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值