python爬取小说例子_案例-爬小说

这是一个Python爬虫示例,用于抓取网络小说。首先定义了一个Downloader类,它从指定的网址获取小说章节列表,并将每个章节的标题和URL存储在列表中。接着,通过遍历该列表,对每个章节发送请求,提取内容并将其写入到文件中。整个过程使用了requests库进行HTTP请求,BeautifulSoup进行HTML解析,实现了小说的全自动下载。
摘要由CSDN通过智能技术生成

~~~py

import requests

import re,sys,time

from bs4 import BeautifulSoup

head={

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.1.2107.204 Safari/537.36'

}

class downloader():

def __init__(self):

self.server='http://book.zongheng.com'

self.target='http://book.zongheng.com/showchapter/929099.html'

self.list=[]

# 获取下载链接

def get_download_url(self):

# target='http://book.zongheng.com/showchapter/929099.html'

req=requests.get(url=self.target)

bf=BeautifulSoup(req.text,"html.parser")

texts=bf.find_all('ul',class_='chapter-list clearfix')

texts=BeautifulSoup(str(texts[1]),"html.parser").find_all('a')

for a in texts:

self.list.append({

'name':a.string,

'url':a.get('href')

})

# 获取每章内容

def get_context(self,urls):

req=requests.get(url=urls)

bf=BeautifulSoup(req.text,"html.parser")

texts=bf.find_all('div',class_='content')

new_text=re.sub('[ | ]+','\n\n',texts[0].text)

return new_text

# 将爬取的数据写入文件

def write_file(self,name,path,context):

write_flag = True

with open(path,'a',encoding='utf-8') as f:

f.write(name+'\n')

f.writelines(context)

f.write('\n\n')

if __name__=='__main__':

dl=downloader()

dl.get_download_url()

i=0

print(len(dl.list))

for n in dl.list:

i += 1

a=dl.get_context(n['url'])

dl.write_file(n['name'],'不知道什么小说.txt',dl.get_context(n['url']))

sys.stdout.write("\r")

sys.stdout.write(" 已下载:%.1f%%" % float(i/len(dl.list)*100))

sys.stdout.flush()

~~~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值