【发布时间】:2019-01-18 20:30:37
【问题描述】:
我正在尝试阅读 MorningStar 中的 keyStat 并了解在 JSON 中扭曲的 HTML 数据。到目前为止,我可以提出一个可以通过 Beautifulsoup 获取 json 的请求:
url = 'http://financials.morningstar.com/ajax/keystatsAjax.html?t=tou&culture=en-CA®ion=CAN'
lm_json = requests.get(url).json()
ksContent = BeautifulSoup(lm_json["ksContent"],"html.parser")
现在我有点想知道 html 数据为“ksContent”,其中包含作为表格的实际数据。我不是 html 的粉丝,我想知道如何才能将它全部变成一个漂亮的 pandas 数据框?由于表格很长,这里是其中的一些:
<table cellpadding="0" cellspacing="0" class="r_table1 text2">
<colgroup>
<col width="23%"/>
<col span="11" width="7%"/>
</colgroup>
<thead>
<tr>
<th align="left" scope="row"></th>
<th align="right" id="Y0" scope="col">2008-12</th>
<th align="right" id="Y1" scope="col">2009-12</th>
<th align="right" id="Y2" scope="col">2010-12</th>
<th align="right" id="Y3" scope="col">2011-12</th>
<th align="right" id="Y4" scope="col">2012-12</th>
<th align="right" id="Y5" scope="col">2013-12</th>
<th align="right" id="Y6" scope="col">2014-12</th>
<th align="right" id="Y7" scope="col">2015-12</th>
<th align="right" id="Y8" scope="col">2016-12</th>
<th align="right" id="Y9" scope="col">2017-12</th>
<th align="right" id="Y10" scope="col">TTM</th>
</tr>
</thead>
<tbody>
<tr class="hr">
<td colspan="12"></td>
</tr>
<tr>
<th class="row_lbl" id="i0" scope="row">Revenue <span>CAD Mil</span></th>
<td align="right" headers="Y0 i0">—</td>
<td align="right" headers="Y1 i0">40</td>
<td align="right" headers="Y2 i0">212</td>
<td align="right" headers="Y3 i0">349</td>
<td align="right" headers="Y4 i0">442</td>
<td align="right" headers="Y5 i0">759</td>
<td align="right" headers="Y6 i0">1,379</td>
<td align="right" headers="Y7 i0">1,074</td>
<td align="right" headers="Y8 i0">1,125</td>
<td align="right" headers="Y9 i0">1,662</td>
<td align="right" headers="Y10 i0">1,760</td>
</tr> ...
它定义了一个标题 tr, Y0, Y1 ... Y10 作为实际日期,下一个 tr 引用它。
感谢您的帮助!
【问题讨论】:
-
df_list = pd.read_html(ksContent.prettify())(将 pandas 导入为 pd 后)将为您提供 8 个数据帧的列表。我没有看到原始表格,所以我不确定它应该是什么样子,但你可以通过这些来挑选,例如df_list[0].head()看看其中一个或几个是你要找的。span>
标签: python-3.x pandas beautifulsoup