From 4e6a4f0abbca75b6052b903795bac8b4d7ea3bdb Mon Sep 17 00:00:00 2001 From: liuwei Date: Thu, 3 Apr 2025 09:04:24 +0800 Subject: [PATCH] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base/func_news.py | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/base/func_news.py b/base/func_news.py index dcf27ce..97d0f08 100644 --- a/base/func_news.py +++ b/base/func_news.py @@ -62,21 +62,35 @@ class News(object): # 初始化一个空字符串来存储结果 output = f"当前日期:{current_date} {current_weekday_chinese}\n\n" - response = requests.get(url) + try: + response = requests.get(url, headers=self.headers, timeout=10) + response.raise_for_status() # 检查请求是否成功 - if response.status_code == 200: - post = response.json() - # 提取content列表 - str = post['data']['cards'][0]['content'] - # 遍历列表,并格式化每个字典的title, url,然后添加到output字符串中 - for index, article in enumerate(str, start=1): - title = article['word'].replace(" ", "_") - # url = article['url'] - # 使用f-string格式化字符串,并添加到output中 - output += f"{index} :#{title}\n" - - # 输出最终的字符串(这里只是为了展示,实际上你可以根据需要处理这个字符串) - return output + if response.status_code == 200: + post = response.json() + # 提取content列表 - 避免使用str作为变量名 + content_list = post.get('data', {}).get('cards', []) + + if content_list and len(content_list) > 0: + news_items = content_list[0].get('content', []) + + # 遍历列表,并格式化每个字典的title, url,然后添加到output字符串中 + for index, article in enumerate(news_items, start=1): + if isinstance(article, dict) and 'word' in article: + title = article['word'].replace(" ", "_") + # url = article.get('url', '') + # 使用f-string格式化字符串,并添加到output中 + output += f"{index} :#{title}\n" + + # 输出最终的字符串 + return output + else: + self.LOG.error(f"获取百度新闻失败,状态码: {response.status_code}") + return "获取百度新闻失败,请稍后再试" + + except Exception as e: + self.LOG.error(f"获取百度新闻时出错: {e}") + return f"获取百度新闻时出错: {e}" def get_eng_news(self,website): if website == 'nbc':