【问题标题】:How skip to another loop in python if no data returned by the API?如果 API 没有返回数据,如何跳到 python 中的另一个循环?
【发布时间】:2020-07-18 16:45:06
【问题描述】:

我有一个 Python 代码,它遍历多个位置并从第三方 API 提取数据。下面是代码sublocation_ids是来自目录的位置ID。

从代码中可以看出,数据被转换为数据框,然后保存到 Excel 文件中。我目前面临的问题是,如果 API 没有为特定位置返回 publication_timestamp 的数据,则循环停止并且不继续,并且我收到如下代码所示的错误。

如果 API 没有返回数据,我该如何避免这种情况并跳到另一个循环?

for sub in sublocation_ids:
    city_num_int = sub['id']
    city_num_str = str(city_num_int)
    city_name = sub['name']
    filter_text_new = filter_text.format(city_num_str)
    data = json.dumps({"filters": [filter_text_new], "sort_by":"created_at", "size":2})
    r = requests.post(url = api_endpoint, data = data).json()
    articles_list = r["articles"] 
    articles_list_normalized = json_normalize(articles_list)
    df = articles_list_normalized
    df['publication_timestamp'] = pd.to_datetime(df['publication_timestamp'])
    df['publication_timestamp'] = df['publication_timestamp'].apply(lambda x: x.now().strftime('%Y-%m-%d'))
    df.to_excel(writer, sheet_name = city_name)
writer.save()   

关键错误:publication_timestamp

【问题讨论】:

  • TryExcept

标签: python python-3.x pandas api dataframe


【解决方案1】:

修改这段代码:

df = articles_list_normalized
if 'publication_timestamp' in df.columns:
    df['publication_timestamp'] = pd.to_datetime(df['publication_timestamp'])
    df['publication_timestamp'] = df['publication_timestamp'].apply(lambda x: x.now().strftime('%Y-%m-%d'))
    df.to_excel(writer, sheet_name = city_name)
else:
    continue

如果 API 字面上没有返回数据,即{},那么您甚至可以在对其进行规范化之前进行检查:

if articles_list:
    df = json_normalize(articles_list)
    # ... rest of code ...
else:
    continue

【讨论】:

  • 工作就像一个魅力:)
猜你喜欢
  • 1970-01-01
  • 2015-08-18
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
相关资源
最近更新 更多