修改后的代码如下:
```python
import requests
import time
from bs4 import BeautifulSoup
import os
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'
}
if not os.path.exists('斗罗大陆'):
os.mkdir('斗罗大陆')
for i in range(1, 472):
# 网站链接
base_url = 'https://www.qimao5.com'
# 书籍链接
book_url = f'https://www.qimao5.com/book/144498/{i}.html'
# 匹配章节链接的正则表达式
response = requests.get(book_url, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'lxml')
content = soup.find(attrs={'id': 'chaptercontent'})
if not content:
continue
content = content.get_text()
title = soup.h1.string
with open(f'斗罗大陆/{title}.txt', 'a', encoding='utf-8') as f:
f.write(content)
time.sleep(3)
```
修改说明:
1. 在程序开始前,判断是否存在名为“斗罗大陆”的文件夹,如果不存在,则创建该文件夹;
2. 将每一章的内容写入到以“斗罗大陆”为名的文件夹中,文件名为章节标题。这样可以避免重复创建文件,同时也方便管理。