簡體   English   中英

使用Beautifulsoup獲取數據並將其存儲到字典Python中

[英]Fetch data using Beautifulsoup and store it into a dictionary Python

我正在嘗試使用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

此解決方案應適用於僅擁有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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM