首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在python中将HTML表格转换为终端上的表格

在Python中将HTML表格转换为终端上的表格可以使用BeautifulSoup库来解析HTML,并使用tabulate库将表格数据格式化为终端上的表格。

首先,需要安装BeautifulSoup和tabulate库。可以使用以下命令来安装:

代码语言:txt
复制
pip install beautifulsoup4
pip install tabulate

接下来,可以使用以下代码将HTML表格转换为终端上的表格:

代码语言:txt
复制
from bs4 import BeautifulSoup
from tabulate import tabulate

html = """
<table>
  <tr>
    <th>姓名</th>
    <th>年龄</th>
    <th>性别</th>
  </tr>
  <tr>
    <td>张三</td>
    <td>25</td>
    <td>男</td>
  </tr>
  <tr>
    <td>李四</td>
    <td>30</td>
    <td>女</td>
  </tr>
</table>
"""

soup = BeautifulSoup(html, 'html.parser')

table = []
headers = []
for th in soup.find_all('th'):
    headers.append(th.text)
table.append(headers)

for tr in soup.find_all('tr'):
    row = []
    for td in tr.find_all('td'):
        row.append(td.text)
    if row:
        table.append(row)

table_str = tabulate(table, headers='firstrow', tablefmt='grid')
print(table_str)

运行以上代码,将会输出如下的终端表格:

代码语言:txt
复制
+--------+------+--------+
| 姓名   | 年龄 | 性别   |
+========+======+========+
| 张三   | 25   | 男     |
+--------+------+--------+
| 李四   | 30   | 女     |
+--------+------+--------+

这样,你就可以将HTML表格转换为终端上的表格了。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券