用Python3写一个简单的爬小说的爬虫(下)

import requests
import re
from bs4 import BeautifulSoup

#获取整个页面,https://www.biquge5200.cc/14_14621/笔趣阁某本小说的网址
url = 'https://www.biquge5200.cc/14_14621/'
response = requests.get(url)
html = response.text

#清洗数据
title = re.findall('<title>(.*?)</title>', html, re.S)[0]#得到小说名
fb = open('%s.txt' % title, 'w', encoding='utf-8')#保存文件以小说名命名
list = re.findall('<dl>(.*?)</dl>' , html, re.S)[0]#得到整个列表
soup = BeautifulSoup(list, 'html.parser')#解析列表
chapter_list = soup.find_all('a')#找到列表里面所有的a标签,得到每个章节的连接和章节名

'''
分别打印输出a标签的href和value
for link in links:
    print(link.name, link['href'], link.get_text())

'''
for chapter in chapter_list:
    chapter_url = chapter['href']
    chapter_title = chapter.get_text()
    chapter_response = requests.get(chapter_url)
    chapter_html = chapter_response.text
    chapter_soup = BeautifulSoup(chapter_html,'html.parser')
    chapter_content_list = chapter_soup.find_all('p')#小说的内容都放在p标签里面
    fb.write(chapter_title)#章节名
    fb.write('\n')
    for chapter_content in chapter_content_list:
        print(chapter_content.get_text())#打印到控制台
        fb.write(chapter_content.get_text())#写进文档里
        fb.write('\n')
    
    fb.write('\n')
    fb.write('\n')
    #exit()先打印一章,看是否出错,用exit来测试




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值