【问题标题】:How to create a JSON file from scraped HTML data如何从抓取的 HTML 数据创建 JSON 文件
【发布时间】:2020-07-04 11:07:41
【问题描述】:

我想抓取一个 HTML 表格并将其存储到一个 JSON 文件中。我成功抓取了 html 表数据,但不知道如何将 抓取的 数据存储到 JSON 文件中。

这是我的代码:

import requests  
from bs4 import BeautifulSoup  

r = requests.get('url')

soup = BeautifulSoup(r.text, 'html.parser')
resultset = soup.find_all('table', attrs={'style':'font-weight:bold'})
records = []  
for result in resultset:  
    heading = result.find('tr')
    records.append((heading))
print(heading)

我得到表单中的HTML表格数据:

<table>
    <thead>
        <tr>
            <th>Serial Number</th>
            <th>Name</th>
            <th>number1</th>
            <th>number2</th>
            <th>number3</th>
            <th>number4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>John</td>
            <td>22</td>
            <td>4</td>
            <td>12</td>
            <td>18</td>
        </tr>
        <tr>
            <td>1</td>
            <td>Chris</td>
            <td>26</td>
            <td>6</td>
            <td>10</td>
            <td>1</td>
        </tr>
    </tbody>
</table>

如何将此 HTML 表格数据存储在 JSON 文件中。 所需的 JSON 格式为:

[
 {
   "Serial Number": 1,
   "Name": "John",
   "number1": 22,
   "number2": 4,
   "number3": 12,
   "number4": 18
 },
 {
   "Serial Number": 1,
   "Name": "Chris",
   "number1": 26,
   "number2": 6,
   "number3": 10,
   "number4": 1
 }
]

【问题讨论】:

  • 你能澄清一下到底是什么问题吗?请参阅How to Ask、help center。
  • 我想从 HTML 表中创建一个 JSON 文件,如上一部分所示,这与 stackoverflow.com/questions/18544634/… 中所做的差不多
  • 这就是目标,在你的帖子中已经说明了,我问的是这个问题。

标签: python html json web-scraping beautifulsoup


【解决方案1】:

看 html 是一种 xml,你有 xml 解析器,试试其中一个。 作为提示,我给你这个网站:https://www.codespeedy.com/how-to-convert-xml-to-json-in-python/

【讨论】:

  • 很高兴为您提供帮助,我刚刚完成了 google foobar 挑战,所以我很喜怒无常。
  • 谢谢维克多。但是,根据上述提示,我无法在我的 JSON 中获取所需格式的数据。我还应该做什么?
  • 看现在很难说你应该不用你的代码做什么,所以如果你能评论你得到的东西,我可以正确回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 2011-11-10
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
相关资源
最近更新 更多