python - 如何将json数据从url打印到excel?

标签 python json parsing csv url

import urllib 
import json
import re
import csv
from bs4 import BeautifulSoup

game_code = open("/Users//Desktop/PYTHON/gc.txt").read()

game_code = game_code.split("\r")


for gc in game_code:

    htmltext =urllib.urlopen("http://cluster.leaguestat.com/feed/index.php?feed=gc&key=f109cf290fcf50d4&client_code=ohl&game_id="+gc+"&lang_code=en&fmt=json&tab=pxpverbose")

    soup= BeautifulSoup(htmltext, "html.parser")
    j= json.loads(soup.text)
    summary = ['GC'],['Pxpverbose']
    for event in summary:
        print gc, ["event"]

我似乎无法访问库来打印正确的标题和行。我最终想将特定行导出到 csv。我 2 天前下载了 python,所以我很新。我的一个项目需要这个数据集。任何建议或指导将不胜感激。

如果有人想看的话,这里有一些游戏代码。谢谢

21127,20788,20922,20752,21094,21196,21295,21159,21128,20854,21057

最佳答案

这里有一些想法:

  • 我想指出优秀的 requests作为 urllib 的替代品来满足您在 Python 中的所有 HTTP 需求(您可能需要 pip install requests)。
  • requests 带有内置的 json 解码器(您不需要 BeautifulSoup)。
  • 事实上,您已经导入了一个很棒的模块 (csv) 来打印标题和数据行。您还可以使用此模块将数据写入文件。
  • 您的数据在 Python 中作为字典 (dict) 返回,这是一种由 索引的数据结构。您可以使用这些键访问数据中的(我认为这就是您所说的“特定行”的意思)。

许多可能的方法之一来完成你想要的:

import requests
import csv

game_code = open("/Users//Desktop/PYTHON/gc.txt").read()
game_code = game_code.split("\r")

for gc in game_code:
    r = requests.get("http://cluster.leaguestat.com/feed/index.php?feed=gc&key=f109cf290fcf50d4&client_code=ohl&game_id="+gc+"&lang_code=en&fmt=json&tab=pxpverbose")
    data = r.json()

    with open("my_data.csv", "a") as csvfile:
        wr = csv.writer(csvfile,delimiter=',')
        for summary in data["GC"]["Pxpverbose"]:
            wr.writerow([gc,summary["event"]])
            # add keys to write additional values;
            # e.g. summary["some-key"].  Example: 
            # wr.writerow([gc,summary["event"],summary["id"]])

关于python - 如何将json数据从url打印到excel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37105876/

相关文章:

javascript - 如何读取json并在html中显示

c++ - 使用 boost 属性树读取 int 数组

parsing - 捕获包含 - 但不以破折号结尾的名称

regex - 正则表达式是否用于构建解析器?

python - 如何检查一个单词是否适合指定数量的列?

python - 如何根据每个组为数据框着色?

javascript - 将 ajax 响应传递给 django 模板

Python Django - 执行 django-admin-script.py - 打开文件而不是创建项目

javascript - Javascript 意外 token B 中的 JSON

php - 从所有先前的消息和元数据中提取电子邮件本身(Sendgrid Parse API/PHP)?