【问题标题】:Python - Selecting Specific Results to Place in ExcelPython - 选择要放入 Excel 的特定结果
【发布时间】:2016-12-02 09:09:13
【问题描述】:

编辑:我做了很多努力,我现在正试图从我的 JSON 文件中解析出单列,而不是整行。但是,每当我尝试操纵我的 DataFrame 以获得我想要的结果时,我都会收到一个错误。

错误是: 第 52 行,在 df = pd.DataFrame.from_dict(mlbJson['stats_sortable_player']['queryResults']['name_display_first_last']) KeyError: 'name_display_first_last'

只有当我尝试添加另一个参数时才会发生这种情况,例如我取出 ['row'] 并添加 ['name_display_first_last'] 以获取每个玩家的名字和姓氏。如果我留在 ['row'] 中,它会编译,但会给我所有数据,我只想要某些 sn-ps。

任何帮助将不胜感激!谢谢。

import requests
import pandas as pd
from bs4 import BeautifulSoup

# Scraping data from MLB.com

target = [MLB JSON][1]
mlbResponse = requests.get(target)
mlbJson = mlbResponse.json()
# Placing response in variable


# Collecting data and giving it names in pandas
data = {'Team': team, 'Line': line}
# places data table format, frames the data
table = pd.DataFrame(data)
# Creates excel file named Scrape
writer = pd.ExcelWriter('Scrape.xlsx')
# Moves table to excel taking in Parameters , 'Name of DOC and Sheet on that Doc'
table.to_excel(writer, 'Lines 1')


#stats = {'Name': name, 'Games': games, 'AtBats': ab, 'Runs': runs, 'Hits': hits, 'Doubles': doubles, 'Triples': triples, 'HR': hr, 'RBI': rbi, 'Walks': walks, 'SB': sb}
df = pd.DataFrame.from_dict(mlbJson['stats_sortable_player']['queryResults']['row'])
df.to_excel(writer, 'Batting 2')

# Saves File

writer.save()

【问题讨论】:

    标签: python json excel pandas beautifulsoup


    【解决方案1】:

    看起来网站通过另一个请求异步加载数据到不同的 URL。你得到的响应有空的<datagrid><\datagrid>标签,soup2.select_one("#datagrid").find_next("table")返回None

    您可以使用浏览器中的网络选项卡下的开发人员工具找到实际加载数据的 URL,如下所示:

    http://mlb.mlb.com/pubajax/wf/flow/stats.splayer?season=2016&sort_order=%27desc%27&sort_column=%27avg%27&stat_type=hitting&page_type=SortablePlayer&game_type=%27R%27&player_pool=ALL&season_type=ANY&sport_code=%27mlb%27&results=1000&recSP=1&recPP=50

    您可以修改您的代码以向该 URL 发出请求,该 URL 返回 json

    mlbResponse = requests.get(url)
    mlbJson = mlbResponse.json() # python 3, otherwise use json.loads(mlbResponse.content) 
    df = pd.DataFrame(doc['stats_sortable_player']['queryResults']['row'])
    

    DataFrame 有 54 列,因此我无法在此处显示,但您应该可以选择并重命名您需要的列。

    【讨论】:

    • 感谢您的回复,我还在调整中似乎不太明白,我得到了一个
    • 所以我从那个链接创建汤?当我尝试制作数据框时,我会将要移动到我的 excel 文件中的某些列放在哪里? @user666
    • 您是否尝试运行答案中的代码并查看DataFrame?您可以选择生成的 DataFrame 中的列,并将其保存到 Excel 文件中。这里不需要 BeautifulSoup,因为 URL 返回 JSON。
    • 是的,它部分工作!我通过使用 df.loc[:['tags of columns I want] 解决了剩下的问题,感谢@user666 的帮助!
    猜你喜欢
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多