【问题标题】:How do I remove a column from a table in beautifulsoup (Python)如何从beautifulsoup(Python)中的表中删除一列
【发布时间】:2011-01-23 12:03:06
【问题描述】:

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

【问题讨论】:

    标签: python beautifulsoup html-table


    【解决方案1】:

    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,并且codepeak服务器关闭,所以我无法更新。我最终只使用了beautifulsoup,因为事实证明该列中的每个单元格都有一个特殊的类,所以很容易通过类名删除。
    猜你喜欢
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多