Python简化了HTML表格

时间:2016-05-12 10:20:20

标签: python html beautifulsoup python-requests

有一种很好的方法(例如使用BeautifulSoup)来简化HTML表格。我正在使用请求获取表格并使用BeautifulSoup提取表格,但我需要表格来自:

<table>
    <thead></thead>
    <tbody>
        <tr>
            <td><a id="bar">Some text<br></br><span class="foobar">foo </span><small class="foo">bar!</small></a></td>
        </tr>
    </tbody>
</table>

为:

<table>
    <thead></thead>
    <tbody>
        <tr>
            <td>Some text\nfoo bar!</td>
        </tr>
    </tbody>
</table>

通过一种简单的方式,我想不必去每个标签并使用 soup.get_text()

1 个答案:

答案 0 :(得分:1)

您可以使用换行符替换br:

h = """<table>
    <thead></thead>
        <tr>
            <td><a id="bar">Some text<br><br/><span class="foobar">foo </span><small class="foo">bar!</small></a></td>
        </tr>
</table>"""


from bs4 import BeautifulSoup

soup = BeautifulSoup(h)

td = soup.select_one("#bar")
td.br.replace_with("\n") 

td.replace_with(td.text)


print(repr(soup))

这给了你:

<html><body><table>\n<thead></thead>\n<tr>\n<td>Some text\nfoo bar!</td>\n</tr>\n</table></body></html>