import requests import time from bs4 import BeautifulSoup q = 1 for i in range(1,472): time.sleep(3) headers =

动态 未结 0 124
小小草
小小草 LV1 2023年9月23日 23:40 发表
你可以将爬取到的内容保存到一个txt文件中,例如: ``` import requests import time from bs4 import BeautifulSoup for i in range(1, 472): time.sleep(3) 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/{i}.html' # 匹配章节链接的正则表达式 response = requests.get(book_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', 'w', encoding='utf-8') as f: f.write(content) ``` 在这个例子中,我们使用`with open()`语句打开一个文件,并指定写入模式和编码方式。然后使用`f.write()`方法将爬取到的内容写入文件中。每次循环都会创建一个新的文件,文件名为章节标题。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复