吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1544|回复: 1
收起左侧

[Python 原创] Python浏览网页提取关键字“最新消息”的程序

[复制链接]
daxia2004 发表于 2025-3-9 17:10
本帖最后由 苏紫方璇 于 2025-3-10 13:36 编辑

[Python] 纯文本查看 复制代码
import requests
from bs4 import BeautifulSoup

def extract_latest_news(url):
    # 设置请求头模拟浏览器访问‌:ml-citation{ref="1,5" data="citationList"}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    }
   
    try:
        # 发送HTTP请求‌:ml-citation{ref="2,4" data="citationList"}
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = response.apparent_encoding  # 自动检测编码
        
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # 查找包含关键字的元素‌:ml-citation{ref="1,3" data="citationList"}
            results = []
            for element in soup.find_all(['h1', 'h2', 'h3', 'p', 'div']):  # 常见文本容器标签
                text = element.get_text(strip=True)
                if '最新消息' in text:
                    # 提取关联链接‌:ml-citation{ref="6,7" data="citationList"}
                    link = element.find_parent('a', href=True)
                    results.append({
                        "text": text,
                        "link": link['href'] if link else url
                    })
            
            return results
        else:
            print(f"请求失败,状态码:{response.status_code}")
            return []
            
    except Exception as e:
        print(f"发生异常:{str(e)}")
        return []

# 使用示例
if __name__ == "__main__":
    target_url = "https://news.example.com"  # 替换为目标网址
    news_list = extract_latest_news(target_url)
   
    print(f"找到{len(news_list)}条最新消息:")
    for index, news in enumerate(news_list, 1):
        print(f"{index}. 内容:{news['text']}")
        print(f"   链接:{news['link']}\n")

免费评分

参与人数 1吾爱币 +5 热心值 +1 收起 理由
苏紫方璇 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

苏紫方璇 发表于 2025-3-10 13:36
插入代码可以参考这篇帖子
【公告】发帖代码插入以及添加链接教程(有福利)
https://www.52pojie.cn/thread-713042-1-1.html
(出处: 吾爱破解论坛)
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-10-22 18:40

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表