【问题标题】:Getting text from table row with beautiful soup用漂亮的汤从表格行中获取文本
【发布时间】:2015-11-07 00:46:57
【问题描述】:

我想用美丽的汤从标签之间提取文本。到目前为止,我有:

def table_to_text(html):
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html)
    trs = soup.findAll('tr')
    for tr in trs:
        print 'row '
        print tr.findAll(['td','th']).text

这给了我这样的输出:

row 
[<td> AAA </td>, <td>Chi</td>, <td></td>, <td class="center"><span class="blue">1353</span>/<span class="red">23</span></td>]/n

我想让输出看起来像:

[ AAA , Chi, , 1353, 23]

我该怎么做?

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    .findAll 返回一个列表,因此您需要另一个这样的 for 循环:

    [el.text for el in sp.find_all(['td', 'th']) if el.text]
    

    【讨论】:

    • 非常感谢你的作品!请问findAll和find_all有什么区别?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2017-10-16
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多