【发布时间】: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