【问题标题】:BS4: removing <a> tagsBS4:删除 <a> 标签
【发布时间】:2020-01-04 18:25:55
【问题描述】:

我正在使用 BeautifulSoup 4,我有以下 HTML:

<tr>
  <td>London <a href="/company/mcrt/5" target="_blank">10 vol</a> 54 page</td>
</tr>

我正在尝试仅删除“a”标签并将文本保留在其中,如下所示:

<tr>
  <td>London 10 vol 54 page</td>
</tr>

bs4有什么办法吗?

【问题讨论】:

  • 当然有可能,你试过什么?你遇到什么问题?请提供您遇到问题的代码
  • 我找到了 .text 方法,该方法删除了所有标签并返回“London 10 vol 54 page”。但我不想删除 标签。

标签: python html parsing beautifulsoup html-parsing


【解决方案1】:

您正在搜索.unwrap()方法:

txt = '''<tr>
  <td>London <a href="/company/mcrt/5" target="_blank">10 vol</a> 54 page</td>
</tr>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(txt, 'html.parser')

soup.a.unwrap()

print(soup)

打印:

<tr>
<td>London 10 vol 54 page</td>
</tr>

【讨论】:

    猜你喜欢
    • 2012-10-15
    • 1970-01-01
    • 2021-03-18
    • 2016-10-08
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多