我正在嘗試檢索每本書的所有頁數并計算總數。以下解決方案有效,但沒有使用 API 提供的分頁功能。
import requests
from requests.exceptions import HTTPError
total_number_of_pages = []
def get_all_books():
try:
response = requests.get("https://www.anapioficeandfire.com/api/books?page=1&pageSize=15")
response.raise_for_status()
json_response = response.json()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
return json_response
def sum_of_total_number_of_pages():
total_number_of_pages = sum(pages["numberOfPages"] for pages in get_all_books())
print(f"The total number of pages of all books is {total_number_of_pages}")
sum_of_total_number_of_pages()
我參考了這個答案并利用了 API 的分頁功能
import requests
from requests.exceptions import HTTPError
baseurl = "https://www.anapioficeandfire.com/api/"
endpoint = "books"
def get_number_of_pages_for_each_book():
number_of_pages_for_each_book = []
try:
response = requests.get(f"{baseurl}{endpoint}")
json_response = response.json()
response.raise_for_status()
for pages in json_response:
number_of_pages_for_each_book.append(pages['numberOfPages'])
while 'next' in response.links:
response = requests.get(response.links['next']['url'])
json_response = response.json()
for pages in json_response:
number_of_pages_for_each_book.append(pages['numberOfPages'])
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
return number_of_pages_for_each_book
def calculate_total_number_of_pages(number_of_pages):
total_amount_of_pages = sum(number_of_pages)
print(f"The total number of pages is {total_amount_of_pages}")
data = get_number_of_pages_for_each_book()
calculate_total_number_of_pages(data)
如果我json_response要從get_number_of_pages_for_each_book()方法回傳,它只回傳來自 while 回圈的資料,而不是初始 GET 請求。這就是我選擇創建一個串列并附加兩個請求中的資料的原因。
我想知道是否有更好的方法來構建代碼。
uj5u.com熱心網友回復:
代碼看起來不錯。
在 Python 中很while True受歡迎break
import requests
from requests.exceptions import HTTPError
baseurl = "https://www.anapioficeandfire.com/api/"
endpoint = "books"
def get_number_of_pages_for_each_book():
number_of_pages_for_each_book = []
url = f"{baseurl}{endpoint}"
try:
while True:
response = requests.get(url)
json_response = response.json()
for pages in json_response:
number_of_pages_for_each_book.append(pages['numberOfPages'])
if 'next' not in response.links:
break
url = response.links['next']['url']
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
return number_of_pages_for_each_book
def calculate_total_number_of_pages(number_of_pages):
total_amount_of_pages = sum(number_of_pages)
print("The total number of pages is", total_amount_of_pages)
data = get_number_of_pages_for_each_book()
calculate_total_number_of_pages(data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465330.html
