【问题标题】:Python convert HTML table to jsonPython将HTML表格转换为json
【发布时间】:2019-06-13 04:35:31
【问题描述】:

我有一个这样的 html 表。尝试使用 pandas.read_html 和 beautifulsoup,。真的很郁闷,求救!!

这是我原来的python代码:

url = 'http://financials.morningstar.com/ajax/keystatsAjax.html?t=wja&culture=en-CA&region=CAN'
lm_json = requests.get(url).json()
ksContent = BeautifulSoup(lm_json["ksContent"],"html.parser")
table = ksContent.find("table", {'class': "r_table1 text2"})
jsonD = json.dumps(table.text)
jsonL = json.loads(jsonD)

'table' 会有 html 表格,但 json 转换会变成纯文本。

【问题讨论】:

标签: python json pandas


【解决方案1】:

这可以使用 python pandas 解决:

first_table = result.find("table")
df = pd.read_html(str(first_table))

with open("./table.json", "a+") as f:
    f.write(df[0].to_json(orient='records'))
    f.close()

为我工作。

【讨论】:

    【解决方案2】:

    jsonD = json.dumps(htmlContent.text) 将原始 HTML 内容转换为 JSON 字符串表示。 jsonL = json.loads(jsonD) 将 JSON 字符串解析回常规字符串/unicode 对象。这会导致无操作,因为dumps() 所做的任何转义都会被loads() 还原。 jsonL 包含与htmlContent.text 相同的数据。

    【讨论】:

    • 我上传了代码,但是json.dump生成的是纯文本
    猜你喜欢
    • 2015-09-02
    • 2013-07-02
    • 2020-05-09
    • 2020-06-08
    • 2021-07-05
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多