爬取学校新闻网页的标题,时间,内容,发布人并保存至.csv文件中
时间: 2024-05-10 18:20:42 浏览: 18
由于缺少具体的学校新闻网页链接和网页结构,以下代码仅供参考,需要根据实际情况进行修改和完善。
```python
import requests
from bs4 import BeautifulSoup
import csv
# 模拟浏览器发送请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 发送请求,获取网页内容
url = 'http://www.example.com/news'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
# 获取新闻列表
news_list = soup.find_all('div', class_='news-item')
# 遍历新闻列表,获取标题,时间,内容,发布人
news_data = []
for news in news_list:
title = news.find('a', class_='news-title').get_text()
time = news.find('span', class_='news-time').get_text()
content = news.find('div', class_='news-content').get_text()
author = news.find('span', class_='news-author').get_text()
news_data.append([title, time, content, author])
# 将数据保存至.csv文件中
with open('news.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['标题', '时间', '内容', '发布人'])
writer.writerows(news_data)
```
在实际应用中,需要根据具体的网页结构和数据格式进行解析和提取。同时,需要注意编码问题,确保数据正确保存至.csv文件中。