使用requests或urllib库,os库以及bs4库爬取特定网页内容。不得使用现成的桌面工具爬取内容。 爬取包括: 1、 广轻新闻,即从以下入口进去的所有新闻(接近1800条) 2、 二级学院“信息技术学院”的新闻。 爬取的新闻内容以及保存方式: 1、 爬取的内容 所有新闻只抽取有效的“标题”,“正文”文本内容,以及本新闻的url地址,其他内容忽略。 如下篇新闻 进入此新闻后,红框部分是需要抽取的内容: 2、保存形式 将所有爬取的内容保存到gdqy目录中。 每条新闻保存到一个文件中,文件名以递增数字为文件名,后缀为.txt
时间: 2024-04-03 10:35:51 浏览: 18
非常好,您需要使用 Python 的 requests 或 urllib 库、os 库和 bs4 库爬取广轻新闻和信息技术学院的新闻,保存方式为每条新闻保存到一个文件中,文件名以递增数字为文件名,后缀为.txt。
首先,您需要安装 requests 和 beautifulsoup4 库。在终端或命令行中输入以下命令可安装:
```
pip install requests
pip install beautifulsoup4
```
接下来,您可以使用以下代码爬取广轻新闻:
```python
import requests
from bs4 import BeautifulSoup
import os
# 设置请求头
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'}
# 设置保存路径
save_path = './gdqy'
# 创建保存路径
if not os.path.exists(save_path):
os.makedirs(save_path)
# 爬取广轻新闻
url = 'http://www.gdqy.edu.cn/'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
news_list = soup.find_all('li', class_='news_li')
# 遍历新闻列表,保存每条新闻到文件
for i, news in enumerate(news_list):
# 获取新闻标题和链接
title = news.find('a').text.strip()
link = url + news.find('a')['href']
# 发送请求,获取新闻内容
news_response = requests.get(link, headers=headers)
news_soup = BeautifulSoup(news_response.content, 'html.parser')
news_content = news_soup.find('div', class_='news_content').text.strip()
# 保存新闻到文件中
filename = '{}/{}.txt'.format(save_path, i+1)
with open(filename, 'w', encoding='utf-8') as f:
f.write(link + '\n')
f.write(title + '\n')
f.write(news_content)
```
请注意爬取时要设置请求头,否则会被网站拦截。此外,还需要创建保存路径,遍历新闻列表并保存每条新闻到文件中。
接下来,您可以使用以下代码爬取信息技术学院的新闻:
```python
import requests
from bs4 import BeautifulSoup
import os
# 设置请求头
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'}
# 设置保存路径
save_path = './gdqy'
# 创建保存路径
if not os.path.exists(save_path):
os.makedirs(save_path)
# 爬取信息技术学院的新闻
url = 'http://xxjs.gdqy.edu.cn/info/iList.jsp?cat_id=10026'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
news_list = soup.find_all('li', class_='news_li')
# 遍历新闻列表,保存每条新闻到文件
for i, news in enumerate(news_list):
# 获取新闻标题和链接
title = news.find('a').text.strip()
link = 'http://xxjs.gdqy.edu.cn' + news.find('a')['href']
# 发送请求,获取新闻内容
news_response = requests.get(link, headers=headers)
news_soup = BeautifulSoup(news_response.content, 'html.parser')
news_content = news_soup.find('div', class_='news_content').text.strip()
# 保存新闻到文件中
filename = '{}/{}.txt'.format(save_path, i+1)
with open(filename, 'w', encoding='utf-8') as f:
f.write(link + '\n')
f.write(title + '\n')
f.write(news_content)
```
与广轻新闻的爬取类似,需要设置请求头、创建保存路径、遍历新闻列表并保存每条新闻到文件中。
最后,您可以在终端或命令行中运行以上代码,爬取新闻并保存到 gdqy 目录下。