使用Python爬虫实时监控行业新闻案例

news/2025/2/19 15:11:57/

目录

    • 背景
    • 环境准备
    • 请求网页数据
    • 解析网页数据
    • 定时任务
    • 综合代码
    • 使用代理IP提升稳定性
    • 运行截图与完整代码
    • 总结

在互联网时代,新闻的实时性和时效性变得尤为重要。很多行业、技术、商业等领域的新闻都可以为公司或者个人发展提供有价值的信息。如果你有一项需求是要实时监控某个行业的新闻,自动化抓取并定期输出这些新闻,Python爬虫可以帮你轻松实现这一目标。

本文将通过一个案例,带你一步一步实现一个简单的Python爬虫,用于实时监控新闻网站的数据。

背景

在某些行业中,获取最新的新闻信息至关重要。通过定期抓取新闻网站的头条新闻,我们可以为用户提供行业热点的动态变化。本文的目标是创建一个爬虫,定期访问一个新闻网站,获取新闻的标题和链接,并打印出来。

环境准备

在开始编写代码之前,我们需要安装几个Python的第三方库:

  • requests:用于发送HTTP请求。
  • beautifulsoup4:用于解析网页HTML内容。
  • schedule:用于设置定时任务,使爬虫能够自动运行。

可以通过以下命令安装这些库:

python">pip install requests beautifulsoup4 schedule

请求网页数据

在爬取新闻之前,我们首先要获取目标网页的HTML内容。通过requests库可以方便地发送GET请求,并返回页面内容。以下是请求网页的代码:

python">import requests# 请求头配置
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}# 爬虫请求函数
def fetch_news(url):try:print(f"Attempting to fetch: {url}")  # 调试信息response = requests.get(url, headers=HEADERS, timeout=10)print(f"Status code: {response.status_code}")  # 打印状态码if response.status_code == 200:return response.textelse:print(f"Failed to fetch {url}. Status code: {response.status_code}")return Noneexcept requests.exceptions.RequestException as e:print(f"Error fetching {url}: {e}")return None
  • HEADERS用于模拟浏览器访问,避免被网站屏蔽。
  • fetch_news函数发送GET请求并返回网页内容。如果请求成功,则返回HTML内容。

解析网页数据

一旦我们获取了网页的HTML内容,就需要解析这些内容,提取出我们关心的数据(例如新闻标题和链接)。这里我们使用beautifulsoup4来解析HTML并提取新闻数据。

python">from bs4 import BeautifulSoup# 解析Al Jazeera新闻页面
def parse_aljazeera_page(page_content):soup = BeautifulSoup(page_content, 'html.parser')news_items = []articles = soup.find_all('a', class_='u-clickable-card__link')print(f"Found {len(articles)} articles on Al Jazeera")for article in articles:title_tag = article.find('h3')if title_tag:title = title_tag.text.strip()link = article['href']if link.startswith('http'):news_items.append({'title': title,'link': link})else:# 如果链接是相对路径,拼接完整链接full_link = f"https://www.aljazeera.com{link}"news_items.append({'title': title,'link': full_link})return news_items
  • BeautifulSoup用于解析HTML内容。
  • parse_aljazeera_page函数从页面中找到所有新闻条目,并提取每个新闻的标题和链接。

定时任务

爬虫的核心功能是定期抓取新闻信息。为了实现这一点,我们可以使用schedule库来设置定时任务,定时运行爬虫

python">import schedule
import time# 定时执行任务
def run_scheduler():# 每隔10分钟抓取一次新闻schedule.every(10).minutes.do(monitor_news)while True:print("Scheduler is running...")  # 调试信息schedule.run_pending()time.sleep(1)
  • 我们使用schedule.every(10).minutes.do(monitor_news)设置每10分钟执行一次monitor_news函数,获取并输出新闻。

综合代码

将之前的部分代码整合在一起,并加入一个监控新闻的函数:

python">def monitor_news():url = 'https://www.aljazeera.com/'page_content = fetch_news(url)if page_content:news_items = parse_aljazeera_page(page_content)if news_items:print(f"News from {url}:")for news in news_items:print(f"Title: {news['title']}")print(f"Link: {news['link']}")print("-" * 50)else:print(f"No news items found at {url}.")else:print(f"Failed to fetch {url}.")if __name__ == '__main__':monitor_news()  # 手动调用一次,看看是否能抓取新闻run_scheduler()  # 继续运行定时任务

使用代理IP提升稳定性

爬虫在运行时,可能会遇到反爬机制导致IP被封禁的情况。为了规避这一问题,我们可以通过配置代理IP来提高爬虫的稳定性。下面是如何使用亮数据代理API的配置示例:

python"># 代理API配置
PROXY_API_URL = 'https://api.brightdata.com/proxy'
API_KEY = 'your_api_key'  # 请替换为实际API密钥
  • PROXY_API_URL:亮数据的代理API接口地址。
  • API_KEY:你的API密钥,用于认证API请求。

通过修改爬虫的请求函数,将代理配置加到请求中,可以让爬虫通过多个IP地址进行请求,从而降低被封禁的风险:

python">def fetch_news_with_proxy(url):try:print(f"Attempting to fetch with proxy: {url}")  # 调试信息response = requests.get(url,headers=HEADERS,proxies={"http": PROXY_API_URL, "https": PROXY_API_URL},timeout=10)print(f"Status code: {response.status_code}")  # 打印状态码if response.status_code == 200:return response.textelse:print(f"Failed to fetch {url}. Status code: {response.status_code}")return Noneexcept requests.exceptions.RequestException as e:print(f"Error fetching {url}: {e}")return None

运行截图与完整代码

运行截图:

在这里插入图片描述
完整代码如下

python">import requests
from bs4 import BeautifulSoup
import schedule
import time# 请求头配置
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}# 亮数据代理API配置
PROXY_API_URL = 'https://api.brightdata.com/proxy'
API_KEY = 'your_api_key'  # 请替换为实际API密钥# 爬虫请求函数
def fetch_news(url):try:print(f"Attempting to fetch: {url}")  # 调试信息response = requests.get(url, headers=HEADERS, timeout=10)print(f"Status code: {response.status_code}")  # 打印状态码if response.status_code == 200:return response.textelse:print(f"Failed to fetch {url}. Status code: {response.status_code}")return Noneexcept requests.exceptions.RequestException as e:print(f"Error fetching {url}: {e}")return None# 解析Al Jazeera新闻页面
def parse_aljazeera_page(page_content):soup = BeautifulSoup(page_content, 'html.parser')news_items = []articles = soup.find_all('a', class_='u-clickable-card__link')print(f"Found {len(articles)} articles on Al Jazeera")for article in articles:title_tag = article.find('h3')if title_tag:title = title_tag.text.strip()link = article['href']if link.startswith('http'):news_items.append({'title': title,'link': link})else:# 如果链接是相对路径,拼接完整链接full_link = f"https://www.aljazeera.com{link}"news_items.append({'title': title,'link': full_link})return news_items# 定时任务
def run_scheduler():schedule.every(10).minutes.do(monitor_news)while True:print("Scheduler is running...")  # 调试信息schedule.run_pending()time.sleep(1)# 新闻监控函数
def monitor_news():url = 'https://www.aljazeera.com/'page_content = fetch_news(url)if page_content:news_items = parse_aljazeera_page(page_content)if news_items:print(f"News from {url}:")for news in news_items:print(f"Title: {news['title']}")print(f"Link: {news['link']}")print("-" * 50)else:print(f"No news items found at {url}.")else:print(f"Failed to fetch {url}.")# 主程序
if __name__ == '__main__':monitor_news()  # 手动调用一次,看看是否能抓取新闻run_scheduler()  # 继续运行定时任务

通过这一方式,爬虫不仅能抓取并显示新闻内容,还能避开反爬机制,提升抓取稳定性。

总结

通过上述步骤,我们实现了一个简单的Python爬虫,用于实时抓取Al Jazeera新闻网站的数据,并通过定时任务每隔一定时间自动抓取一次。在爬虫运行过程中,可能会遇到反爬机制导致IP被封禁的情况。为了避免这个问题,我们可以通过配置代理IP来提高爬虫的稳定性。


http://www.ppmy.cn/news/1572444.html

相关文章

20250214在ubuntu20.04下使用obs studio录制外挂的1080p的USB摄像头【下载安装】

20250214在ubuntu20.04下使用obs studio录制外挂的1080p的USB摄像头 2025/2/14 9:10 缘起:笔记本电脑在ubuntu20.04下使用Guvcview录制自带的摄像头,各种问题。 1、降帧率。WIN10/11自带的相机应用可以满速30fps,马上重启到ubuntu20.04&#…

Flutter 异步编程利器:Future 与 Stream 深度解析

目录 一、Future:处理单次异步操作 1. 概念解读 2. 使用场景 3. 基本用法 3.1 创建 Future 3.2 使用 then 消费 Future 3.3 特性 二、Stream:处理连续异步事件流 1. 概念解读 2. 使用场景 3. 基本用法 3.1 创建 Stream 3.2 监听 Stream 3.…

C++20 新特性解析

1. 概念(Concepts) 概念是 C++20 引入的一项重要特性,它允许程序员定义类型约束,从而在编译时检查模板参数是否符合某些要求。概念提供了模板参数的限制,使得模板代码更加可读和易于维护。 示例代码: #include <iostream> #include <concepts>// 定义一个…

C++实用技巧之 --- 观察者模式详解

C实用技巧之 — 观察者模式详解 目录 C实用技巧之 --- 观察者模式详解一、系统学习前的思考二、观察者模式详解1. 模式的定义2. 主要角色3. 模式的结构4. 实现步骤5. 优点6. 缺点7. 实际应用7.1 代码实现7.2 说明7.3 高级主题7.4 优点总结7.5 缺点总结7.6 应用原则7.7 相关设计…

如何使用智能化RFID管控系统,对涉密物品进行安全有效的管理?

载体主要包括纸质文件、笔记本电脑、优盘、光盘、移动硬盘、打印机、复印机、录音设备等&#xff0c;载体&#xff08;特别是涉密载体&#xff09;是各保密、机要单位保证涉密信息安全、防止涉密信息泄露的重要信息载体。载体管控系统主要采用RFID射频识别及物联网技术&#xf…

在nodejs中使用RabbitMQ(三)Routing、Topics、Headers

示例一、Routing exchange类型direct&#xff0c;根据消息的routekey将消息直接转发到指定队列。producer.ts 生产者主要发送消息&#xff0c;consumer.ts负责接收消息&#xff0c;同时也都可以创建exchange交换机&#xff0c;创建队列&#xff0c;为队列绑定exchange&#xff…

Spring Boot 的约定优于配置,你的理解是什么?

“约定优于配置” 是 Spring Boot 极为重要的设计理念&#xff0c;它极大地简化了 Spring 应用的开发流程&#xff0c;下面从多个方面详细解释这一理念&#xff1a; 减少配置复杂性 传统开发的痛点 在传统的 Spring 开发里&#xff0c;配置工作相当繁琐。以配置 Spring MVC …

高效训练,深度学习GPU服务器搭建

引言 在AI人工智能时代&#xff0c;深度学习的重要性日益凸显。拥有一台高性能的深度学习GPU服务器成为众多从业者的追求。然而&#xff0c;预算往往是一个限制因素。本文将指导你如何在有限的预算下配置一台性能尽可能拉满的深度学习GPU服务器。 GPU选购关键因素 GPU服务器…