@
metalvest 比如
```python
import requests
from bs4 import BeautifulSoup
import os
# 定义已下载的 URL 集合和有序的网页内容列表
downloaded_urls = set()
pages = []
# 定义递归函数来遍历整个网站的树状结构并提取文本内容
def scrape_website(root_url, url):
# 检查链接是否以根路径开始或者是否与根路径相同
if not url.startswith(root_url) or url == root_url:
return
# 检查该 URL 是否已经下载过,如果是则跳过下载
if url in downloaded_urls:
return
# 发送请求获取网页内容
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 提取网页标题和正文内容
title = soup.title.text.strip()
body = soup.body.text.strip()
# 将该网页的标题和正文内容添加到有序的网页内容列表中
pages.append((title, body))
# 将该 URL 添加到已下载的 URL 集合中
downloaded_urls.add(url)
# 递归遍历子页面链接
for link in soup.find_all('a'):
href = link.get('href')
if href.startswith('http'):
scrape_website(root_url, href)
elif href.startswith('/'):
scrape_website(root_url, root_url + href)
# 指定网站根路径
root_url = '
https://www.example.com/'# 发送请求获取根路径的网页内容
response = requests.get(root_url)
soup = BeautifulSoup(response.content, 'html.parser')
# 从根路径的网页标题中提取文件名
root_title = soup.title.text.strip()
output_filename = root_title + '.txt'
# 调用递归函数来爬取整个网站的树状结构并保存文本内容
scrape_website(root_url, root_url)
# 遍历有序的网页内容列表并将内容合并为一个线性的文本文件
with open(output_filename, 'w') as f:
for title, body in pages:
f.write(title + '\n\n')
f.write(body + '\n\n')
```