4
我有一个html表格,我想删除一列。使用BeautifulSoup或任何其他Python库做到这一点的最简单方法是什么?我如何从美丽的表格中删除一列(Python)
我有一个html表格,我想删除一列。使用BeautifulSoup或任何其他Python库做到这一点的最简单方法是什么?我如何从美丽的表格中删除一列(Python)
lxml.html更适合操作HTML,IMO。这里有一些代码会删除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)
结果:
<table>
<tr>
<th>head 1</th>
<th>head 3</th>
</tr>
<tr>
<td>item 1</td>
<td>item 3</td>
</tr>
</table>
感谢您的响应。不幸的是,我所使用的lxml版本不支持fragment_fromstring,并且codespeak服务器关闭了,所以我无法更新。我最终使用了beautifulsoup,因为事实证明,该列中的每个单元格都有一个特殊的类,所以很容易通过类名删除。 – jedberg