【问题标题】:Python HTML Table to JSON [duplicate]Python HTML表到JSON [重复]
【发布时间】:2017-08-11 13:30:58
【问题描述】:

我需要一些帮助来尝试在 Python 中将多个 HTML 表转换为 JSON。 我有以下几点:

[<table>\n<tr><th nowrap="">FRUIT</th><td>APPLE</td></tr>\n<tr><th nowrap="">COLOR</th><td>GREEN</td></tr>\n</table>, <table>\n<tr><th nowrap="">FRUIT</th><td>BANANA</td></tr>\n<tr><th nowrap="">COLOR</th><td>YELLOW</td></tr>\n</table>]

我想要实现的是以 JSON 格式输出它:

[
    {
        "FRUIT": "APPLE", 
        "COLOR": "GREEN"
    }, 
    {
        "FRUIT": "BANANA", 
        "COLOR": "YELLOW"
    }
]

【问题讨论】:

  • 我试过这种方式。它不起作用:
  • print json.dumps(dict(str_tbl)) ValueError: 字典更新序列元素 #0 的长度为 1; 2 是必需的

标签: python json regex beautifulsoup


【解决方案1】:
In [49]: for table in soup.find_all('table'):
    ...:     keys = [th.get_text(strip=True)for th in table.find_all('th')]
    ...:     values = [td.get_text(strip=True) for td in table.find_all('td')]
    ...:     d = dict(zip(keys, values))
    ...:     print(d)
    ...:     
    ...:     
    ...:     
{'FRUIT': 'APPLE', 'COLOR': 'GREEN'}
{'FRUIT': 'BANANA', 'COLOR': 'YELLOW'}

【讨论】:

    猜你喜欢
    • 2016-05-31
    • 2021-09-02
    • 2016-07-05
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多