选择任意新闻网站,完成网站数据的爬取和存储.. 1.能够正确爬取到网页的源代码。(10 分) 能够选择beautifulsoup. xpath 或者re正则中的任意一种方式, 完成数据的解析。(爬取所选网站的各类信息(至少5条),并输出爬取到的数据:) (30 分) 实现多页爬取。(10分) 能够选择selenium或者Scrapy进行动态网页数据的爬取。(20 分} 将爬取的数据进行存储。可以存储为记事本文件、csV文件、EXCEL文件等任意-一种(15
时间: 2024-03-18 21:43:03 浏览: 16
好的,我选择爬取新浪新闻网站的数据并存储到CSV文件中。以下是实现的步骤:
1. 首先,我们需要安装必要的库来进行网页爬取和解析。可以使用以下命令来安装它们:
```
pip install requests
pip install beautifulsoup4
pip install pandas
```
2. 接下来,我们需要使用requests库向新浪新闻网站发送请求,并获取响应内容。以下是示例代码:
```python
import requests
url = 'https://news.sina.com.cn/'
response = requests.get(url)
if response.status_code == 200:
print('请求成功!')
else:
print('请求失败!')
```
3. 然后,我们需要使用beautifulsoup4库将获取的响应内容解析成HTML文档,并提取出新闻标题和链接。以下是示例代码:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
news_list = soup.select('.news-item')
data_list = []
for news in news_list:
title = news.select_one('.news-title').text.strip()
link = news.select_one('.url').get('href')
time = news.select_one('.time').text.strip()
source = news.select_one('.source').text.strip()
keywords = news.select_one('.keywords').text.strip()
data_list.append([title, link, time, source, keywords])
print('爬取到的数据:')
for data in data_list:
print(data)
```
4. 实现多页爬取。我们可以通过修改URL中的页码参数来爬取多页数据。以下是示例代码:
```python
import requests
from bs4 import BeautifulSoup
data_list = []
for page in range(1, 3): # 爬取前2页数据
url = f'https://news.sina.com.cn/roll/#pageid=153&lid=2509&k=&num=50&page={page}'
response = requests.get(url)
if response.status_code == 200:
print(f'第{page}页请求成功!')
else:
print(f'第{page}页请求失败!')
continue
soup = BeautifulSoup(response.text, 'html.parser')
news_list = soup.select('.list_009 .d_list')
for news in news_list:
title = news.select_one('.list_009 a').text.strip()
link = news.select_one('.list_009 a').get('href')
time = news.select_one('.list_009 .time').text.strip()
source = news.select_one('.list_009 .media_name').text.strip()
keywords = news.select_one('.list_009 .keywords').text.strip()
data_list.append([title, link, time, source, keywords])
print('爬取到的数据:')
for data in data_list:
print(data)
```
5. 最后,我们可以使用pandas库将爬取到的数据存储到CSV文件中。以下是示例代码:
```python
import pandas as pd
df = pd.DataFrame(data_list, columns=['标题', '链接', '时间', '来源', '关键词'])
df.to_csv('news.csv', index=False, encoding='utf-8-sig')
print('数据已保存到CSV文件中!')
```
完整代码如下所示: