【问题标题】:beautifulsoup get last tag from snippet, if tag exists如果标签存在,beautifulsoup 从片段中获取最后一个标签
【发布时间】:2015-10-22 04:11:42
【问题描述】:

这里是 html sn-p 1:

<td class="firstleft lineupopt-name" style=""><a href="/link/link_url?id=222" title="Donald Trump" target="_blank">Trump, Donald</a>&nbsp;<span style="color:#666;font-size:10px;">B</span> &nbsp;<span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>

这里是 html sn-p 2:

<td class="firstleft lineupopt-name" style=""><a href="/link/link_url2?id=221" title="Hillary Clinton" target="_blank">Clinton, Hillary</a> &nbsp;<span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>

这是我的相关代码:

all = cols[1].find_all('span')
for ele in all:
    if (ele is not None):
        ttt = cols[1].span.text
    else:
        ttt = 'none'

问题:我的代码在这两种情况下都有效,但对于 html sn-p 2,它从第一个 span 标签中获取内容。在这两种情况下,如果标签存在,我只想从最后一个 span 标签中获取内容。如何才能做到这一点?

【问题讨论】:

    标签: python html parsing beautifulsoup html-parsing


    【解决方案1】:

    一种直接的方法是通过-1 index 获取最后一个元素:

    ttt = all[-1].text if all else 'none'
    

    我也尝试使用CSS selector 来处理它,但BeautifulSoup 不支持last-childlast-of-typenth-last-of-type,并且仅支持nth-of-type 伪类。

    【讨论】:

      【解决方案2】:

      我在 conda env 中使用 bs4 v4.9.1 进行了测试,现在 nth-last-of-type(1) 可以了。

      【讨论】:

        【解决方案3】:

        BS4 现在支持last-child,因此可能的方法是:

        soup.select('td span:last-child')
        

        要获取文本,只需迭代结果集。

        示例

        from bs4 import BeautifulSoup
        
        html='''
        <td class="firstleft lineupopt-name" style=""><a href="/link/link_url?id=222" title="Donald Trump" target="_blank">Trump, Donald</a>&nbsp;<span style="color:#666;font-size:10px;">B</span> &nbsp;<span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
        <td class="firstleft lineupopt-name" style=""><a href="/link/link_url2?id=221" title="Hillary Clinton" target="_blank">Clinton, Hillary</a> &nbsp;<span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
        '''
        soup = BeautifulSoup(html)
        
        [t.text for t in soup.select('td span:last-child')]
        

        输出

        ['TTT', 'TTT']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-03-25
          • 1970-01-01
          • 2020-12-06
          • 1970-01-01
          • 2014-08-16
          • 2020-12-22
          • 2021-12-06
          相关资源
          最近更新 更多