使用python爬取小说(附python源码)

本文档展示了如何使用Python requests和正则表达式模块爬取并整理《龙族》系列小说的章节和内容,通过定义多个函数实现网站链接抓取、文本解析和内容输出,适用于初学者学习网络爬虫技术。

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

import requests ###爬虫模块,获取网页文本
import re       ###正则表达式模块,从网页文本中提取所需要的信息
###### gettext(url):输入网站链接 url,返回该网站的文本
def gettext(url):
    r = requests.get(url,timeout=30)
    r.encoding = 'apparent_encoding'
    return r.text
###### 输入目录链接 url,返回各章节链接数组
def geturl(url):
    text=gettext(url)
    chapter_info_list=re.findall(r'<li><a href="(.*?)">',text)
    del(chapter_info_list[0])
    return chapter_info_list
###### 输入网站 url,返回该网站文本数组
def getline(url):
    text = gettext(url)
#print(text,file=open("序章.txt",'a',encoding='utf-8'))
    title=re.findall(r'<h1>(.*?)</h1>',text)
    line=re.findall(r'<span class="calibre[2-9]">(.*?)</span>',text)
    all = title+line
    return(all)
##### 输入数组,生成txt文件
def my_print(line,my_name):
    for i in line:
        print(i+'\n',file=my_name)
##### 主函数
def main():
    my_file=open("龙族.txt",'x',encoding='utf-8')
    url='http://www.yuedu88.com/longzu1/'
    url_list=geturl(url)
    for i in url_list:
        line=getline(i)
        my_print(line,my_file)
main()

2021年2月23日12:39:57

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值