【酷酷的知识】仅用30行Python代码就能获取实时新闻数据?

前言

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

观察网页

我们首先通过浏览器进入珠海市生态环境局网站,通过浏览器开发者工具观察页面结构,确定我们需要爬取的数据位置和网址。

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

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

在标头栏,我们找到我们的请求头,以便我们后续访问:

在预览栏,我们找到了数据源,以便我们后续爬取:

在响应框,我们找到了存储数据的元素,文本被装在了一个类名为wendangListCdiv标签下,日期被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文件。这个爬虫可以方便地用于定期获取最新的新闻信息,为后续数据分析和可视化提供了基础。

相关推荐
choke2338 小时前
[特殊字符] Python异常处理
开发语言·python
玄同7659 小时前
从 0 到 1:用 Python 开发 MCP 工具,让 AI 智能体拥有 “超能力”
开发语言·人工智能·python·agent·ai编程·mcp·trae
小瑞瑞acd9 小时前
【小瑞瑞精讲】卷积神经网络(CNN):从入门到精通,计算机如何“看”懂世界?
人工智能·python·深度学习·神经网络·机器学习
火车叼位10 小时前
也许你不需要创建.venv, 此规范使python脚本自备依赖
python
火车叼位10 小时前
脚本伪装:让 Python 与 Node.js 像原生 Shell 命令一样运行
运维·javascript·python
孤狼warrior10 小时前
YOLO目标检测 一千字解析yolo最初的摸样 模型下载,数据集构建及模型训练代码
人工智能·python·深度学习·算法·yolo·目标检测·目标跟踪
Katecat9966310 小时前
YOLO11分割算法实现甲状腺超声病灶自动检测与定位_DWR方法应用
python
玩大数据的龙威11 小时前
农经权二轮延包—各种地块示意图
python·arcgis
ZH154558913111 小时前
Flutter for OpenHarmony Python学习助手实战:数据库操作与管理的实现
python·学习·flutter
belldeep11 小时前
python:用 Flask 3 , mistune 2 和 mermaid.min.js 10.9 来实现 Markdown 中 mermaid 图表的渲染
javascript·python·flask