我想建造一个刮刀。我写了这段代码,但它不断出错。如果有人可以提供帮助,我将不胜感激。
def fetch_json(api_link, timeout=10):
try:
response = requests.get(api_link, timeout=timeout)
if response.status_code == 200:
return response.json()
else:
print(f"Failed to fetch data from API for link: {api_link}")
return None
except requests.exceptions.Timeout:
print(f"Timeout occurred while fetching data for link: {api_link}. Skipping...")
return None
except requests.exceptions.RequestException as e:
print(f"Error occurred while fetching data for link {api_link}: {e}")
return None
api_link = "https://apiv2.cricket.com.au/web/players/list?isActive=1&teamId=&jsconfig=eccn%3Atrue&format=json"
player_data= fetch_json(api_link)
name = []
if player_data:
players = player_data['players']
for player in players:
id = "".join(players['id'])
displayname = "".join(players['displayname'])
name.append({
"id" : player.get("id"),
"displayname" : player.get("displayname")
})
print(f"Player Name Retrived")
player_name = pd.DataFrame(name)
它在 id 列上显示错误,我似乎无法解决这个问题。
错误出现在这两行中:
id = "".join(players['id'])
displayname = "".join(players['displayname'])
你正在迭代
players
列表,所以每个
player
已经是字典了。你不需要用
players['id']
访问
id
,直接使用
player['id']
即可。另外,
join
方法用于将字符串列表连接成一个字符串,但
player['id']
和
player['displayname']
应该已经是字符串了,所以不需要使用
join
。
将这两行代码改为:
id = player.get("id")
displayname = player.get("displayname")
修正后的代码:
import requests
import pandas as pd
def fetch_json(api_link, timeout=10):
# ... (代码与之前相同)
api_link = "https://apiv2.cricket.com.au/web/players/list?isActive=1&teamId=&jsconfig=eccn%3Atrue&format=json"
player_data= fetch_json(api_link)
name = []
if player_data:
players = player_data['players']
for player in players:
id = player.get("id")
displayname = player.get("displayname")
name.append({
"id" : id,
"displayname" : displayname
})
print(f"Player Name Retrived")
player_name = pd.DataFrame(name)
修改后,代码应该就能正常运行,并成功提取球员的 ID 和显示名称。
标签:python,json,dataframe From: 78786460