将所有爬取的内容保存到目录中。 每条新闻保存到一个文件中,文件名以递增数字为文件名,后缀为.txt。比如第一条新闻保存到1.txt,第二条保存到2.txt
时间: 2024-04-04 08:33:45 浏览: 16
好的,你可以使用以下 Python 代码实现:
```python
import os
import requests
from bs4 import BeautifulSoup
def save_news(url):
# 发送 HTTP 请求,获取网页内容
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 解析网页,获取新闻标题和正文内容
title_tag = soup.find('h1')
if title_tag is None:
title = ''
else:
title = title_tag.get_text().strip()
content_tags = soup.find_all('div', class_='content')
content = '\n'.join([tag.get_text().strip() for tag in content_tags])
# 生成保存文件的路径和文件名
dir_path = 'news'
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_name = f'{len(os.listdir(dir_path)) + 1}.txt'
file_path = os.path.join(dir_path, file_name)
# 将新闻内容写入文件
with open(file_path, 'w', encoding='utf-8') as f:
f.write(url + '\n')
f.write(title + '\n\n')
f.write(content)
if __name__ == '__main__':
urls = [
'https://www.example.com/article/1',
'https://www.example.com/article/2',
'https://www.example.com/article/3'
]
for url in urls:
save_news(url)
```
你可以将需要爬取的网页 URL 存放在 `urls` 列表中,然后运行代码即可将新闻内容保存到 `news` 目录中。每条新闻保存在以递增数字为文件名的 `.txt` 文件中,文件名为新闻的标题。其中,第一行为新闻的 URL,第二行为新闻标题,第三行及之后为新闻的正文内容。