如何从beautifulsoup(Python)中的表中删除列

jed*_*erg 5 python html-table beautifulsoup

我有一个html表,我想删除一个列.使用BeautifulSoup或任何其他python库最简单的方法是什么?

Rya*_*rom 2

在我看来, lxml.html更适合操作 HTML。下面是一些代码,用于删除 HTML 表格的第二列。

from lxml import html

text = """
<table>
<tr><th>head 1</th><th>head 2</th><th>head 3</th></tr>
<tr><td>item 1</td><td>item 2</td><td>item 3</td></tr>
</table>
"""

table = html.fragment_fromstring(text)

# remove middle column
for row in table.iterchildren():
    row.remove(row.getchildren()[1])

print html.tostring(table, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)

结果:

<table>
<tr>
<th>head 1</th>
<th>head 3</th>
</tr>
<tr>
<td>item 1</td>
<td>item 3</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)