使用Beautifulsoup获取数据并将其存储到字典Python中

时间:2018-06-03 20:10:51

标签: python html dictionary beautifulsoup

我正在尝试使用Beautifulsoap获取html文件。稍后我想通过以JSON格式创建REST API来显示数据。 REST API工作正常。但是,我面临着以预期格式构建数据的问题。所以,我附加了只处理获取数据的Python代码。

HTML: -

<!DOCTYPE html>
<html>
<head>
<style>

table, th, td {
    border: 1px solid black;
}
</style>
</head>

<body>

<table>
  <thead>
    <tr>
      <th>Date</th>
      <th>Savings</th>
      <th>Expenses</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
      <td>$200</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
      <td>$300</td>
    </tr>
  </tbody>
</table>

</body>
</html>


My expected output should be :- 

{
    "data":
        "Savings" : {
             "Janunary" : $100,
             "February" : $80
         },    
        "Expenses" : {
             "January" : $200,
             "February" : $300
        }
}

我编写的Python代码,

bs_content = BeautifulSoup(ra.body, 'html.parser') #this parse the whole html

headers = []
result = defaultdict(dict)

table = bs_content.find_all('table')

if not headers:
    for th in table.find('thead').findAll('th'):
        text = th.text
        headers.append(text)

for tr in table.find('tbody').findAll('tr'):
    tds = tr.findAll('td')
    for header, td in zip(headers, tds):
        value = td.text.strip()

        result[header] = value

return result

因此,result应该像

一样更新
result['savings']['January'] = $100,
result['savings']['February'] = $80,
result['Expenses']['January'] = $200,
result['Expenses']['February'] = $300

1 个答案:

答案 0 :(得分:0)

此解决方案适用于超过2个月的表格。

soup = BeautifulSoup(ra.body, 'lxml')
table = soup.select_one('table')
headers = [header.text for header in table.select('th')][1:]
result = {headers[0]: {}, headers[1]: {}}
for row in table.select('tbody tr'):
    data = [value.text for value in row.select('td')]
    result[headers[0]][data[0]] = data[1]
    result[headers[1]][data[0]] = data[2]
return result