python - 如果API没有返回数据,如何跳到Python中的另一个循环?

标签 python python-3.x pandas api dataframe

我有一个 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()   

Key Error: publication_timestamp

最佳答案

更改这段代码:

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

关于python - 如果API没有返回数据,如何跳到Python中的另一个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61063980/

相关文章:

python - 如何管理反斜杠后带有数字的路径?

python - Pandas value_counts() 中的值分组

python - Pandas - 如何分组和绘制一周中每一天的每个小时

python - 如何从 Airflow 中的 Big Query 获取 SQL 查询的结果?

python - 用于 Python 的 StarUML

Python Pandas 读取带有特定行终止符的 CSV 文件

python - 仅在 Matplotlib 中绘制时间(而不是 DateTime)

python - python smime签名验证问题

python - 通过检查 pandas 数据框来替换单词

python - 您如何将列表分成原始列表中所有重复项的子列表?