【问题标题】:Printing only outer tags in HTML code using BeautifulSoup使用 BeautifulSoup 仅打印 HTML 代码中的外部标签
【发布时间】:2019-11-07 04:56:57
【问题描述】:

整个 HTML 代码的一部分如下所示

<td class="col2">
<a class="reserve" data-target="#myModal" data-toggle="modal"     
href="example.com" rel="nofollow"></a></td>

我发现它使用

soup.find_all('td', class_='col2')

但是我想提取的不是代码的全部部分,而只是

<td class="col2"></td>

可以使用 BeautifulSoup 吗?我知道我可以使用字符串来做到这一点,但我只是好奇。

【问题讨论】:

  • a 标签在 td 内。你的最终目标是什么?

标签: python web-scraping beautifulsoup


【解决方案1】:

您可以将 string 属性设置为空字符串 (''):

html = """
<td class="col2">
<a class="reserve" data-target="#myModal" data-toggle="modal"     
href="example.com" rel="nofollow"></a></td>
"""
soup = BeautifulSoup(html)
x = soup.find('td', class_='col2')
x.string = ''
print(x)

输出

<td class="col2"></td>

这是documentation 讲述的内容:

如果你设置标签的.string属性,标签的内容会被你给的字符串替换

注意:如果标签包含其他标签,它们及其所有内容都将被销毁。

【讨论】:

    【解决方案2】:

    您可以使用extract() 函数提取td.col2 中的所有元素:

    data = '''
    <td class="col2">
    <a class="reserve" data-target="#myModal" data-toggle="modal"
    href="example.com" rel="nofollow"></a></td>'''
    
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(data, 'lxml')
    
    for td in soup.select('td.col2'):
        for t in td.select('*'):
            t.extract()
        print(td)
    

    打印:

    <td class="col2">
    </td>
    

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2016-03-25
      • 2021-09-02
      • 2017-11-20
      • 1970-01-01
      相关资源
      最近更新 更多