前言
在本文中,我们将使用Python中的Requests和BeautifulSoup库,以及Pandas库来构建一个简单的网络爬虫,用于从珠海市生态环境局网站获取新闻数据。我们将探讨如何通过浏览器开发者工具观察网页、分析网页结构,以及使用爬虫技术从中提取有用的信息。
观察网页
我们首先通过浏览器进入珠海市生态环境局网站,通过浏览器开发者工具观察页面结构,确定我们需要爬取的数据位置和网址。

我们通过观察发现,找到需要爬取的信息,我们点击更多内容,跳转到了另一个页面:

鼠标右键点击页面空白处,点击"检查",点击"网络"(Network)后Ctrl+R刷新页面。在文档栏中找到对应本网页地址栏网址尾端(即index.html
)

在标头栏,我们找到我们的请求头,以便我们后续访问:
在预览栏,我们找到了数据源,以便我们后续爬取:

在响应框,我们找到了存储数据的元素,文本被装在了一个类名为wendangListC
的div
标签下,日期被strong
标签承装,网址为a
标签的href
属性,标题为a标签的文本:

点击不同页数,发现网页的地址发生改变,总页数为20,第一页为index.html,2~20页为index
+_
+页数.html
:

代码实现
导入第三方库
安装需要用到的库,在终端输入以下代码:
pythion
pip install requests
pip install beautifulsoup4
pip install pandas
引入需要的第三方库:
python
import requests
import pandas as pd
import os
from bs4 import BeautifulSoup
我们导入了 requests
用于发送网络请求,pandas
用于数据处理,os
用于文件操作,以及 BeautifulSoup
用于解析 HTML。
请求数据
python
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.60'}
for i in range(1, 21):
items = []
if i == 1:
url = 'http://ssthjj.zhuhai.gov.cn/hbxw/index.html'
else:
url = f'http://ssthjj.zhuhai.gov.cn/hbxw/index_{i}.html'
r = requests.get(url=url, headers=headers)
text = r.text
soup = BeautifulSoup(text, 'html.parser')
all_titles = soup.find_all("div", attrs={"class": "wendangListC"})
headers={...}
:设置了请求头,模拟了一个浏览器的请求,防止网站拒绝访问,模拟浏览器行为。for i in range(1,21)
:循环遍历了不同页面的新闻数据,从1到20,构建了不同页面的网址。第一页的网址和后续页的网址稍有不同。r = requests.get(url=url, headers=headers) text = r.text
:发送了一个GET请求,获取页面的HTML文本,requests.get
是用来获取网页内容的函数,headers
是前面设置的请求头,确保你的请求看起来像是来自一个浏览器。soup = BeautifulSoup(text, 'html.parser')
:使用BeautifulSoup解析HTML文本。find_all
函数会找到所有包含class="wendangListC"
的div
标签,这正是包含新闻信息的部分。
解析数据
在循环中,逐一处理每个新闻的标题、链接和日期信息:
python
for title in all_titles:
all_links = title.find_all("a")
all_days = title.find_all("strong")
for link, day in zip(all_links, all_days):
href = link.get('href')
title1 = link.string
day1 = day.string
item = [title1, href, day1]
items.append(item)
我们找到了每个标题的 a
标签和日期的 strong
标签,并使用 zip
函数确保它们是一一对应的。然后,你提取了链接、标题和日期信息,将它们放入 item
列表,最后将 item
添加到 items
列表中。
存储数据
利用 pandas 库,将得到的数据转换为DataFrame,并写入CSV文件:
python
df=pd.DataFrame(items,columns=['标题','网址','日期'])
if not os.path.exists('珠海生态环境部新闻.csv'):
df.to_csv(r'珠海生态环境部新闻.csv', encoding='utf_8_sig', mode='a', sep=',', index=False)
else:
df.to_csv(r'珠海生态环境部新闻.csv', encoding='utf_8_sig', mode='a', header=False, sep=',', index=False)
这段代码检查文件是否存在,如果存在则以追加的方式写入,否则以新建文件的方式写入。
全套代码及运行结果
- 全套代码
python
import requests
import pandas as pd
import os
from bs4 import BeautifulSoup
headers ={'User-Agent':'/'}
for i in range(1,21):
items=[]
if i==1:
url='http://ssthjj.zhuhai.gov.cn/hbxw/index.html'
else:
url =f'http://ssthjj.zhuhai.gov.cn/hbxw/index_{i}.html'
r = requests.get(url=url,headers=headers)
text=r.text
soup =BeautifulSoup(text,'html.parser')
all_titles=soup.findAll("div",attrs={"class":"wendangListC"})
for title in all_titles:
all_links = title.find_all("a")
all_days = title.find_all("strong")
for link, day in zip(all_links, all_days):
href = link.get('href')
title1 = link.string
day1 = day.string
item = [title1, href, day1]
items.append(item)
df=pd.DataFrame(items,columns=['标题','网址','日期'])
if not os.path.exists('珠海生态环境部新闻.csv'):
df.to_csv(r'珠海生态环境部新闻.csv', encoding='utf_8_sig', mode='a', sep=',', index=False)
else:
df.to_csv(r'珠海生态环境部新闻.csv', encoding='utf_8_sig', mode='a', header=False, sep=',', index=False)
- 运行结果

结论
通过这个简单的爬虫项目,我们成功地从珠海市生态环境局网站获取了新闻数据,并将其存储为CSV文件。这个爬虫可以方便地用于定期获取最新的新闻信息,为后续数据分析和可视化提供了基础。