【问题标题】:What are the best practices to handle missing fileds from API response?处理 API 响应中缺失字段的最佳做法是什么?
【发布时间】:2023-01-08 03:03:25
【问题描述】:

我正在使用 Google Books API 获取有关使用 ISBN 编号的书籍的详细信息

ISBN - 国际标准书号是一个数字商业书籍标识符,旨在是唯一的

当使用不同的 ISBN 调用 API 时,响应总是不一样,因为有些书缺少某些字段

requests.get(f"https://www.googleapis.com/books/v1/volumes?q=isbn:{'8180315339'}").json() requests.get(f"https://www.googleapis.com/books/v1/volumes?q=isbn:{'938733077X'}").json()

两个响应的 O/P 将返回不同数量的字段

我可以使用 try & except 来处理错误,但这会继续循环中的下一次迭代,即使用下一个 ISBN 调用 API,如何保存可用信息,并在数据所在的数据框中添加 np.nan失踪


data = requests.get(f"https://www.googleapis.com/books/v1/volumes?q=isbn:{'938733077X'}").json()
# Loop through the items in the "items" field of the JSON data
for item in data['items']:
  # Extract the relevant fields from the item
    try:
        title = item['volumeInfo']['title']
        subtitle = item['volumeInfo']['subtitle']
        authors = item['volumeInfo']['authors']
        publisher = item['volumeInfo']['publisher']
        published_date = item['volumeInfo']['publishedDate']
        description = item['volumeInfo']['description']
        pageCount = item['volumeInfo']['pageCount']
        category = item['volumeInfo']['categories']
        imageS = item['volumeInfo']['imageLinks']['smallThumbnail']
        imageM = item['volumeInfo']['imageLinks']['thumbnail']
        language = item['volumeInfo']['language']
        textSnippet = item['searchInfo']['textSnippet']
    except KeyError:
        continue
# Add the fields to the results list as a tuple
results.append((title, subtitle, authors, publisher, published_date, description, pageCount, category, imageS, imageM, language, textSnippet))

# Create a DataFrame from the results list
df_ = pd.DataFrame(results, columns=['Title', 'Sub Title', 'Authors', 'Publisher', 'Published Date', 'Description', 'Page Count', 'Category', 'imageS', 'imageM', 'Language', 'Text'])

【问题讨论】:

    标签: python google-books-api


    【解决方案1】:

    尝试使用这个

    title = item.get('volumeInfo).get('title') # this way if there is no such field you will get None instead of KeyError
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-25
      • 2016-11-24
      • 2010-10-09
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      相关资源
      最近更新 更多