如果要将每个章节保存到不同的文件中,并且每次循环都将新内容追加到文件末尾,可以将打开文件的模式改为追加模式`'a'`。
以下是修改后的代码:
```
import requests
import time
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.39'
}
# 网站链接
base_url = 'https://www.qimao5.com'
# 书籍链接
book_url = f'https://www.qimao5.com/book/144498/'
# 匹配章节链接的正则表达式
response = requests.get(book_url, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'lxml')
chapter_list = soup.find_all(attrs={'class': 'volume-list'})
for chapter in chapter_list:
for link in chapter.find_all('a'):
chapter_url = base_url + link.get('href')
response = requests.get(chapter_url, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'lxml')
content = soup.find(attrs={'id': 'chaptercontent'})
content = content.get_text()
title = soup.h1.string
with open(f'{title}.txt', 'a', encoding='utf-8') as f:
f.write(content + '\n\n')
time.sleep(3)
```
在这个例子中,我们使用`with open()`语句打开一个文件,并指定追加模式和编码方式。然后使用`f.write()`方法将爬取到的内容写入文件中。每次循环都会将新的章节内容追加到对应的文件末尾,而不是覆盖之前的内容。