python 爬虫入门

本文介绍了一种使用Python爬取网络小说的方法,包括获取小说章节列表及内容,并将其保存为本地文本文件。通过正则表达式提取所需信息,实现小说章节的自动化下载。

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

import requests
import re

# TODO 下载 每一个小说的首页url

# TODO 大循环

# 1. 下载小说首页
novel_url = 'http://www.jingcaiyuedu.com/book/15205/list.html'
response = requests.get(novel_url)
# 处理字符编码 显式的指定,
response.encoding = 'utf-8'
html = response.text # 字符串
# print(html)
# 2. 提取 章节url 非贪婪匹配
title = re.findall(r'<meta name="keywords" content="《(.*?)》',html)[0]
# print(title)
# id = list dl 有两个
dl = re.findall(r'<dl id="list">.*?</dl>',html)[1]
# print(dl)
chapter_info_list = re.findall(r'<a.*?href="(.*?)".*?>(.*?)</a>',dl)
# print(chapter_info_list)

# 数据持久化 写入txt
fb = open('%s.txt'%title,'w',encoding='utf-8')

# 3. 循环的去访问每个章节,提取内容
for chapter_info in chapter_info_list:
    chapter_url = chapter_info[0]
    chapter_title = chapter_info[1]
    # 处理 相对url
    if 'http' not in chapter_url:
        chapter_url = 'http://www.jingcaiyuedu.com%s' % chapter_url
    # 下载章节页面
    chapter_response = requests.get(chapter_url)
    chapter_response.encoding = "utf-8"
    chapter_html = chapter_response.text
    # print(chapter_response.text)
    # 提取内容
    chapter_content = re.findall(r'<script>a1\(\);</script>(.*?)<script>a2\(\);</script>',chapter_html)[0]
    # 清洗数据,把多余的字符处理掉
    chapter_content = chapter_content.replace(' ','')
    chapter_content = chapter_content.replace('<br/>','')
    chapter_content = chapter_content.replace('<br>','')
    chapter_content = chapter_content.replace('&nbsp;','')
    # print(chapter_content)
    # 写入文件
    fb.write(chapter_title)
    fb.write('\n')
    fb.write(chapter_content)
    fb.write('\n')
    # chapter_response.close()
    print(chapter_url)

    # exit()

 

转载于:https://www.cnblogs.com/stono/p/8861710.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值