使用代码爬10.1.88.252:7000网页中章节内容,将每个章节内容以及章节名称爬取下来并且将爬取下来的章节名称匿名为文件夹名称,而且在每个文件夹内拥有相对应的章节内容,并且存储为txt文档在文件夹中,将爬取到的保存到C:\data
时间: 2023-12-06 21:45:22 浏览: 18
以下是Python爬虫代码:
```python
import os
import requests
from bs4 import BeautifulSoup
# 目标网址
url = 'http://10.1.88.252:7000'
# 发送请求
response = requests.get(url)
# 解析HTML
soup = BeautifulSoup(response.content, 'html.parser')
# 获取所有章节的链接
chapter_links = soup.find_all('a', href=True)
# 遍历所有章节
for link in chapter_links:
# 获取章节名称
chapter_name = link.text.strip()
# 获取章节链接
chapter_url = url + link['href']
# 发送请求
chapter_response = requests.get(chapter_url)
# 解析HTML
chapter_soup = BeautifulSoup(chapter_response.content, 'html.parser')
# 获取章节内容
chapter_content = chapter_soup.find('div', {'class': 'content'}).text.strip()
# 创建文件夹
folder_name = os.path.join('C:\\data', chapter_name)
os.makedirs(folder_name, exist_ok=True)
# 创建txt文件并写入章节内容
file_name = os.path.join(folder_name, 'chapter.txt')
with open(file_name, 'w', encoding='utf-8') as f:
f.write(chapter_content)
```
这段代码会将网页中所有章节的内容爬取下来,并且按照章节名称保存在以章节名称命名的文件夹中,每个文件夹中包含一个名为`chapter.txt`的txt文档,存储着相应章节的内容。这些文件夹会被保存在`C:\data`目录下。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)