下面是一個簡單的Python代碼示例,演示如何自制一個小說下載器:
```python
import requests
from bs4 import BeautifulSoup
def get_novel_content(url):
# 發送GET請求獲取網頁內容
response = requests.get(url)
response.encoding = 'utf-8'
html = response.text
# 使用BeautifulSoup解析網頁內容
soup = BeautifulSoup(html, 'html.parser')
# 提取小說內容
novel_content = soup.find('div', {'class': 'novel-content'}).get_text()
return novel_content
def download_novel(novel_url, save_path):
# 發送GET請求獲取小說目錄頁
response = requests.get(novel_url)
response.encoding = 'utf-8'
html = response.text
# 使用BeautifulSoup解析目錄頁
soup = BeautifulSoup(html, 'html.parser')
# 提取小說章節鏈接
chapter_links = soup.find_all('a', {'class': 'chapter-link'})
# 逐個下載章節
for link in chapter_links:
chapter_url = link['href']
chapter_title = link.text
# 獲取章節內容
chapter_content = get_novel_content(chapter_url)
# 保存章節內容到文本文件
with open(save_path, 'a', encoding='utf-8') as f:
f.write(chapter_title + '\n\n')
f.write(chapter_content + '\n\n')
print(f"成功下載章節:{chapter_title}")
print("下載完成!")
# 測試代碼
novel_url = "https://example.com/novel" # 小說目錄頁的URL
save_path = "novel.txt" # 保存小說內容的文件路徑
download_novel(novel_url, save_path)
```
請注意,這只是一個簡單的示例代碼,具體的實現可能需要根據不同的小說網站進行調整。你需要根據目標小說網站的HTML結構和頁面規則,適配代碼中的URL、選擇器等部分。