2013-08-31 218 views
12

我试图将通过BeautifulSoup提取的表转换为JSON。将HTML表转换为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'] 
] 

回答

19

可能是你的数据是一样的东西:

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" 
} 
+0

非常感谢,我得到这是由于一些字符在服务器的响应的编码,一旦我想通了这一点你的回答非常完美错误。再次感谢,祝你有美好的一天。 – declanjscott