繁体   English   中英

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

[英]How do I remove a column from a table in beautifulsoup (Python)

我有一个html表,我想删除一个列。 使用BeautifulSoup或任何其他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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM