某位站长老是问我小说怎么用python下载,我一般都是在八零电子书下载,现成的不好吗?写程序爬不麻烦吗?有这时间还不如看看小姐姐。下面分享一个Python自动下载小说源码,由于我从不在网页看小说,这个小说站是别人提供的,与我无关。
源码如下,将其复制保存为XXX.py文件即可。
复制
# -*- coding:UTF-8 -*-
from bs4 import BeautifulSoup
import requests
import sys
import time
class downloader(object):
def __init__(self,url):
self.target = url # 章节页
self.names = [] # 存放章节名
self.urls = [] # 存放章节链接
self.nums = 0 # 章节数
self.title=""#小说名
def get_one_text(self, url_i):
text = ' '
url_i="https://www.nitianxieshen.com"+url_i
r = requests.get(url=url_i)
r.encoding = r.apparent_encoding
html = r.text
html_bf = BeautifulSoup(html, features='html.parser')
texts=html_bf.find_all('p')
texts[0].decompose()
texts[len(texts)-1].decompose()
for t in texts:
text += str(t)
text = text.replace('<None>', '')
text = text.replace('</None>', '')
text = text.replace('</div>', '\n')
text = text.replace('<br/>', '\n')
text = text.replace('<p>', '\n')
text = text.replace('</p>', '\n')
text = text.replace('<\p>', '\n')
return text
def get_name_address_list(self):
list_a_bf = []
list_a = []
r = requests.get(self.target)
r.encoding = r.apparent_encoding
html = r.text
div_bf = BeautifulSoup(html, features='html.parser')
self.title=div_bf.find('h1').text
div = div_bf.find_all('div',attrs={"id":"play_0"})[0]
li=div.find_all('li')
self.nums=len(li)
for i in range(len(li)):
self.names.append(li[i].find('a').string) # string方法返回章节名
self.urls.append(li[i].find('a').get('href')) # get(‘href’)返回子地址串
print("共:"+str(self.nums)+"章")
def writer(self, name, path, text):
write_flag = True
with open(path, 'a', encoding='utf-8') as f: # 打开目标路径文件
f.write(name + '\n')
f.writelines(text)
f.write('\n\n')
if __name__ == "__main__":
dl = downloader("填入小说章节列表页地址")
dl.get_name_address_list()
print('《'+dl.title+'》开始下载:')
for i in range(dl.nums):
time.sleep(0.2)
try:
dl.writer(dl.names[i], r''+dl.title+'.txt', dl.get_one_text(dl.urls[i]))
except IndexError as e:
print(repr(e))
sys.stdout.write(" 已下载:%.3f%%" % float((i/dl.nums)*100) + '\r'+'当前第:'+str(i)+' 章')
sys.stdout.flush()
print(dl.title+'下载完成')然后将其放在拥有python环境的地方,使用python xxx.py回车运行即可,效果如下:
注意:上面的代码使用了python扩展库,请先安装BeautifulSoup与requests支持。参考代码如下:
复制
pip install beautifulsoup4复制
pip install requests如果提示没有pip工具,请先安装pip工具,参考前面的教程Centos7.X升级默认Python到3.X并安装pip3扩展管理






评论 (0)