【问题标题】:Convert a HTML Table to JSON将 HTML 表转换为 JSON
【发布时间】:2013-09-03 21:00:41
【问题描述】:

我正在尝试将通过 BeautifulSoup 提取的表格转换为 JSON。

到目前为止,我已经设法隔离了所有行,但我不确定如何处理此处的数据。任何建议将不胜感激。

[<tr><td><strong>Balance</strong></td><td><strong>$18.30</strong></td></tr>, 
<tr><td>Card name</td><td>Name</td></tr>, 
<tr><td>Account holder</td><td>NAME</td></tr>, 
<tr><td>Card number</td><td>1234</td></tr>, 
<tr><td>Status</td><td>Active</td></tr>]

(为了便于阅读,我的换行)

这是我的尝试:

result = []
allrows = table.tbody.findAll('tr')
for row in allrows:
    result.append([])
    allcols = row.findAll('td')
    for col in allcols:
        thestrings = [unicode(s) for s in col.findAll(text=True)]
        thetext = ''.join(thestrings)
        result[-1].append(thetext)

这给了我以下结果:

[
 [u'Card balance', u'$18.30'],
 [u'Card name', u'NAMEn'],
 [u'Account holder', u'NAME'],
 [u'Card number', u'1234'],
 [u'Status', u'Active']
]

【问题讨论】:

    标签: python html json beautifulsoup html-table


    【解决方案1】:

    您的数据可能类似于:

    html_data = """
    <table>
      <tr>
        <td>Card balance</td>
        <td>$18.30</td>
      </tr>
      <tr>
        <td>Card name</td>
        <td>NAMEn</td>
      </tr>
      <tr>
        <td>Account holder</td>
        <td>NAME</td>
      </tr>
      <tr>
        <td>Card number</td>
        <td>1234</td>
      </tr>
      <tr>
        <td>Status</td>
        <td>Active</td>
      </tr>
    </table>
    """
    

    我们可以使用此代码从中获取您的结果作为列表:

    from bs4 import BeautifulSoup
    table_data = [[cell.text for cell in row("td")]
                             for row in BeautifulSoup(html_data)("tr")]
    

    如果您不关心顺序,将结果转换为 JSON:

    import json
    print json.dumps(dict(table_data))
    

    结果:

    {
        "Status": "Active",
        "Card name": "NAMEn",
        "Account holder":
        "NAME", "Card number": "1234",
        "Card balance": "$18.30"
    }
    

    如果你需要相同的顺序,使用这个:

    from collections import OrderedDict
    import json
    print json.dumps(OrderedDict(table_data))
    

    这给了你:

    {
        "Card balance": "$18.30",
        "Card name": "NAMEn",
        "Account holder": "NAME",
        "Card number": "1234",
        "Status": "Active"
    }
    

    【讨论】:

    • 非常感谢,我收到一个错误,这是由于服务器响应中某些字符的编码,一旦我发现您的答案完美无缺。再次感谢,祝您有美好的一天。
    猜你喜欢
    • 2014-02-23
    • 2015-09-02
    • 2013-07-02
    • 2021-07-05
    • 2020-05-09
    • 2019-06-13
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多