异常处理

This commit is contained in:
liuwei
2025-04-03 09:04:24 +08:00
parent 4335c82c16
commit 4e6a4f0abb

View File

@@ -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':