python文本处理01

本文介绍了一个使用Python爬取特定小说网站章节内容的方法。通过发送HTTP请求获取网页源代码,并解析提取所需的小说章节链接和内容。该教程适用于希望了解如何自动化抓取小说章节的学习者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

f1 = open('test1', 'r+')
f2 = open('test2', 'a+')

for line in f1.readlines():
    print(len(line))
    if len(line) < 10:
        line = '第{}个\n'.format(line.strip())
        f2.writelines(line)

f1.close()
f2.close()

爬取网站http://www.cdzdgw.com/的小说,需要指定小说的主页地址:
例如:http://www.cdzdgw.com/28_28570/,低维游戏

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#

import requests

response = requests.get("http://www.cdzdgw.com/28_28570/")
data = response.content.decode("gbk").split('\n')

chapter_list = []
for line in data:
    line = line.strip('\r').strip('\t').strip(' ')
    if line.endswith('</a></dd>'):
        line = line.strip('<dd><a href=').strip('</a></dd>').replace('"', '').split(">")
        line[0] = 'http://www.cdzdgw.com' + line[0].replace("'", '').strip(' ')
        chapter_list.append(line)

f2 = open('test02.txt', 'a', encoding='gbk')
n = 1
for chapter in chapter_list[9:]:
    chapter_url = chapter[0]
    chapter_name = chapter[1]

    response_chapter = requests.get(chapter_url)
    chapter_data = response_chapter.content.decode("gbk").split('\n')

    f2.write('\n' + chapter_name + '\n\n')
    for chapter_line in chapter_data[58:]:
        chapter_line = chapter_line.strip('\n').strip('\r').strip('\t').strip(' ')
        if chapter_line.endswith('<br />') and len(chapter_line) > 10:
            data = chapter_line.replace('&nbsp;', '').replace('<br />', '').replace('<div id="content">', '') + '\n'
            f2.write(data)
    n += 1
    print(n)
f2.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值