异常处理
This commit is contained in:
@@ -62,21 +62,35 @@ class News(object):
|
|||||||
# 初始化一个空字符串来存储结果
|
# 初始化一个空字符串来存储结果
|
||||||
output = f"当前日期:{current_date} {current_weekday_chinese}\n\n"
|
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:
|
if response.status_code == 200:
|
||||||
post = response.json()
|
post = response.json()
|
||||||
# 提取content列表
|
# 提取content列表 - 避免使用str作为变量名
|
||||||
str = post['data']['cards'][0]['content']
|
content_list = post.get('data', {}).get('cards', [])
|
||||||
# 遍历列表,并格式化每个字典的title, url,然后添加到output字符串中
|
|
||||||
for index, article in enumerate(str, start=1):
|
if content_list and len(content_list) > 0:
|
||||||
title = article['word'].replace(" ", "_")
|
news_items = content_list[0].get('content', [])
|
||||||
# url = article['url']
|
|
||||||
# 使用f-string格式化字符串,并添加到output中
|
# 遍历列表,并格式化每个字典的title, url,然后添加到output字符串中
|
||||||
output += f"{index} :#{title}\n"
|
for index, article in enumerate(news_items, start=1):
|
||||||
|
if isinstance(article, dict) and 'word' in article:
|
||||||
# 输出最终的字符串(这里只是为了展示,实际上你可以根据需要处理这个字符串)
|
title = article['word'].replace(" ", "_")
|
||||||
return output
|
# 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):
|
def get_eng_news(self,website):
|
||||||
if website == 'nbc':
|
if website == 'nbc':
|
||||||
|
|||||||
Reference in New Issue
Block a user