该代码适用于下面这个小说网站(给这个网站打广告)
小说网
import os
import requests
from bs4 import BeautifulSoup
def parseHtml(url, fictionName):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0"}
response = requests.get(url, headers=headers)
response.encoding = 'gbk'
html = response.text
info = BeautifulSoup(html, "html.parser")
title = info.find_all('h1', class_="articleH1")
paragraphs = info.find_all('p')
title = title[0].text
with open(fictionName + '.txt', mode='a', encoding='utf8') as file:
file.write('\n' + title + '\n')
for i in range(len(paragraphs) - 2):
file.write(paragraphs[i].text + '\n')
if __name__ == '__main__':
firstChapterURL = input('输入小说第一章的URL:')
firstChapterURL = firstChapterURL.strip()
lastChapterURL = input('输入小说最后一章的URL:')
lastChapterURL = lastChapterURL.strip()
fictionName = input('你想给这个文本起什么名字?:')
firstChapterNumber = int(firstChapterURL.split('/')[-1].split('.')[0])
lastChapterNumber = int(lastChapterURL.split('/')[-1].split('.')[0])
if firstChapterNumber >= firstChapterNumber:
downloadChapterNumber = 1
for i in range(firstChapterNumber, lastChapterNumber - 1, -1):
url = firstChapterURL.split('.html')[0][:-len(str(firstChapterNumber))] + str(i) + '.html'
parseHtml(url, fictionName)
print("\033[37;41m 下载第" + str(downloadChapterNumber) + "章完成 \033[0m")
downloadChapterNumber += 1
if int(firstChapterNumber) < int(firstChapterNumber):
downloadChapterNumber = 1
for i in range(firstChapterNumber, lastChapterNumber + 1, 1):
url = firstChapterURL.split('.html')[0][:-len(str(firstChapterNumber))] + str(i) + '.html'
parseHtml(url, fictionName)
print("\033[37;41m 下载第" + str(downloadChapterNumber) + "章完成 \033[0m")
downloadChapterNumber += 1
print('文本保存在:\'' + os.getcwd() + '\' 它的名字:\'' + fictionName + '.txt\'')