You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Finviz新闻爬取Python代码 仅输出当日新闻无内容时返回指定提示

调整后可实现仅输出当日新闻的完整代码

核心改动点

  • 补全原代码缺失的pandas、datetime依赖导入
  • 新增Finviz平台的日期格式匹配逻辑,自动识别当日新闻
  • 新增空数据判断分支,当日无新闻时直接输出“No news today”
import numpy as np
import pandas as pd
from datetime import datetime
from bs4 import BeautifulSoup as soup
from urllib.request import Request, urlopen

pd.set_option('display.max_colwidth', 20)

# 输入股票代码
symbol = input('请输入股票代码: ')
print ('正在获取' + symbol + '的相关数据...\n')

# 初始化爬虫配置
url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()
html = soup(webpage, "html.parser")

# 获取新闻并筛选当日内容
def get_today_news():
    try:
        # 提取新闻表格
        news = pd.read_html(str(html), attrs = {'class': 'fullview-news-outer'})[0]
        links = []
        for a in html.find_all('a', class_="tab-link-news"):
            links.append(a['href'])
        
        # 整理新闻数据框
        news.columns = ['日期', '新闻标题']
        news['文章链接'] = links
        news = news.set_index('日期')

        # 匹配当日日期格式
        today_date_str = datetime.today().strftime('%b-%d')
        # 筛选当日新闻:Finviz当日新闻日期列仅显示时间,无日期前缀,历史新闻为「月-日 时间」格式
        today_news = news[news.index.str.startswith(today_date_str) | (~news.index.str.contains('-'))]
        
        return today_news if len(today_news) > 0 else "No news today"

    except Exception as e:
        return "No news today"

# 输出结果
print ('\n今日新闻: ')
print(get_today_news())

内容的提问来源于stack exchange,提问作者Leah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:27:05