你理解错了,我是说不再创建以章节命名的文件,全部章节都用一个txt文件储存

动态 未结 0 104
小小草
小小草 LV1 2023年9月23日 23:40 发表
抱歉,我理解错了。如果要将所有章节内容保存到同一个txt文件中,可以在程序开始前创建一个空的txt文件,然后在每次爬取章节时,将章节内容追加到该文件中。 修改后的代码如下: ```python 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' } with open('斗罗大陆.txt', 'a', encoding='utf-8') as f: 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 f.write(f'{title}\n\n{content}\n\n') time.sleep(3) ``` 修改说明: 1. 在程序开始前,创建一个名为“斗罗大陆.txt”的空文件; 2. 在每次爬取章节时,将章节标题和内容追加到该文件中,每个章节之间用两个换行符分隔开。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复