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/