from bs4 import BeautifulSoup as soup
s = soup(html, 'html.parser').table
h, [_, *d] = [i.text for i in s.tr.find_all('th')], [[i.text for i in b.find_all('td')] for b in s.find_all('tr')]
result = [dict(zip(h, i)) for i in d]
from bs4 import BeautifulSoup
import json
xml_data = """
[[your xml data]]"""if __name__ == '__main__':
model = BeautifulSoup(xml_data, features='lxml')
fields = []
table_data = []
for tr in model.table.find_all('tr', recursive=False):
for th in tr.find_all('th', recursive=False):
fields.append(th.text)
for tr in model.table.find_all('tr', recursive=False):
datum = {}
for i, td inenumerate(tr.find_all('td', recursive=False)):
datum[fields[i]] = td.text
if datum:
table_data.append(datum)
print(json.dumps(table_data, indent=4))
Share
Post a Comment
for "Convert Html Table With A Header To Json - Python"
Post a Comment for "Convert Html Table With A Header To Json - Python"