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

Python中为新闻对象添加image属性失败,求助排查问题

问题分析与修复方案

核心问题

你遇到的问题主要来自两个关键错误:

  1. 错误调用FastAPI路由函数获取数据
  2. 目标对象类型限制(FeedParserDict无法保留新增属性并序列化)

具体修复步骤

1. 分离业务逻辑与路由

不要直接调用FastAPI路由函数create_news_article,它返回的是JSONResponse对象而非原始数据。把文章抓取逻辑抽成独立异步函数:

async def fetch_news_article(url: str):
    from newsplease import NewsPlease
    import requests

    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
        'Content-type': 'application/json',
    }

    # 修复headers参数传递错误
    result = requests.get(url, headers=headers)

    status = "SUCCESS" if result.status_code == 200 else "FAILED"
    if status != "SUCCESS":
        return {"status": status, "newsArticle": None}

    news_article = NewsPlease.from_html(result.content.decode(), url=url)
    # 将NewsPlease对象转为普通字典,方便后续处理
    news_article_dict = news_article.__dict__ if hasattr(news_article, '__dict__') else dict(news_article)
    return {"status": status, "newsArticle": news_article_dict}

然后修改路由函数调用这个逻辑:

@app.get("/news-article/")
async def create_news_article(url: str):
    return await fetch_news_article(url)

2. 转换Feed对象为普通字典

google_news.top_news()返回的entries元素是FeedParserDict类型,这种对象仅保留RSS解析时的预设字段,新增属性不会被JSON序列化器识别。需要先转为普通字典再添加字段:

async def insert_image(news):
    entries = news.get("entries", [])
    for index, item in enumerate(entries):
        try:
            link = item.link
            # 调用独立的业务函数而非路由
            article_data = await fetch_news_article(link)
            
            if article_data["status"] != "SUCCESS" or not article_data["newsArticle"]:
                continue
                
            article_image_url = article_data["newsArticle"].get("image_url")
            if not article_image_url:
                continue

            # 将FeedParserDict转为普通字典
            item_dict = dict(item)
            item_dict["image"] = article_image_url
            # 替换原列表中的元素
            news["entries"][index] = item_dict
        except Exception as e:
            print(f"处理item出错: {item}, 错误信息: {str(e)}\n")

3. 保留原路由逻辑

你的create_news_latest路由无需修改,依然保持:

@app.get("/latest")
async def create_news_latest():
    news = google_news.top_news()
    await insert_image(news)
    return {"news": news}

为什么之前的方法无效?

  • Option1/3:给FeedParserDict对象新增属性,这类对象的序列化逻辑只处理预设字段,新增属性不会被包含在返回结果中。
  • Option2:insert是列表方法,而item是字典类对象,调用方式错误。
  • Option4:FeedParserDict不支持直接通过键赋值新增字段(部分版本的feedparser库限制了这种操作)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:32:07