Как удалить столбец из таблицы в beautifulsoup (Python) - PullRequest
5 голосов
/ 04 марта 2010

У меня есть HTML-таблица, и я хотел бы удалить столбец. Какой самый простой способ сделать это с BeautifulSoup или любой другой библиотекой python?

1 Ответ

2 голосов
/ 04 марта 2010

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>
...