用python请求刮json

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用python请求刮json相关的知识,希望对你有一定的参考价值。

这不是我第一次抓取数据,但确实感觉就像这样。

import csv
import requests
import os

outfile = open("Labs_StartingGoalies.csv","a",newline='')
writer = csv.writer(outfile)
header=[
    "Home_Tm"]

writer.writerow(header)

req = requests.get('https://www.fantasylabs.com/api/lines/4/12-20-2017/startinggoalies') 
data = req.json()['GoalieMatchups']

for i, teams in enumerate(data):
    for i, team in enumerate(teams['Properties']):
        print (team)

输出:

EventId
EventDate
EventDateTime
TimeOfDay
Stadium
HomeTeam
HomeEventTeamId
HomeGoalie
HomeTwitterName
HomePrimarySourceKey
HomeGoalieId
HomeGoalieSalary_DK
HomeGoalieSalary_FD
HomeGoalieStatus
HomeGoalieText
HomeModifiedDate
HomeSourceText
HomeSourceURL
HomeMoneyLine
HomeMoneylineChange
HomeVegasPoints
VisitorTeam
VisitorEventTeamId
VisitorGoalie
VisitorTwitterName
VisitorPrimarySourceKey
VisitorGoalieId
VisitorGoalieSalary_DK
VisitorGoalieSalary_FD
VisitorGoalieStatus
VisitorGoalieText
VisitorModifiedDate
VisitorSourceText
VisitorSourceURL
VisitorMoneyLine
VisitorMoneylineChange
VisitorVegasPoints

下一个代码:

import csv
import requests
import os

outfile = open("Labs_StartingGoalies.csv","a",newline='')
writer = csv.writer(outfile)
header=[
    "Home_Tm"]

writer.writerow(header)

req = requests.get('https://www.fantasylabs.com/api/lines/4/12-20-2017/startinggoalies') 
data = req.json()['GoalieMatchups']

for i, teams in enumerate(data):
    for i, team in enumerate(teams['Properties']):
        HomeTeam = team['HomeTeam']
        print (HomeTeam)

错误:File "C:/Python36/Projects/NHL/Labs_Teams.py", line 17, in <module> HomeTeam = team['HomeTeam'] TypeError: string indices must be integers

这个Json有点难以阅读。通常我会使用Mozilla,但它不会以正常方式显示。我想开始从第一个output的列表中提取数据,但所有不同的尝试都很短。谢谢参观!

答案

for循环应修改如下,

for i, teams in enumerate(data):
    HomeTeam = teams['Properties']['HomeTeam']
    print (HomeTeam)

这将输出

Columbus Blue Jackets
Philadelphia Flyers
Calgary Flames

你不需要内循环,因为teams['Properties']是一个字典,而不是一个列表。

编辑:此外,由于您没有使用计数器,因此您不需要枚举已经是列表的数据

for teams in data:
    HomeTeam = teams['Properties']['HomeTeam']
    print (HomeTeam)
另一答案

你有使用枚举的原因吗?你可能想做这样的事情:

for teams in data:
    HomeTeam = teams['Properties']['HomeTeam']
    print (HomeTeam)

结果:

Columbus Blue Jackets
Philadelphia Flyers
Calgary Flames

以上是关于用python请求刮json的主要内容,如果未能解决你的问题,请参考以下文章

如何刮内容?

python常用代码片段总结

在 Python3 中使用 BeautifulSoup4 刮价格 Udemy 网站

用 Scrapy 和 Selenium 进行刮擦

asp 如何请求 json

python 将循环刮到pd数据帧