2017-03-20 16 views
1

複数のHTMLテーブルをPythonのJSONに変換しようとすると助けが必要です。 私はfollwing持っている:私は何を達成しようとしていることはJSONで出力することにあるPython HTML Table to 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>] 

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

私はその方法を試してみました。 – QEWR

+0

print json.dumps(dict(str_tbl)) ValueError:辞書更新シーケンス要素#0の長さが1です。 2が必要です – QEWR

答えて

2
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'}