【问题标题】:How to remove links from tags in html?如何从html中的标签中删除链接?
【发布时间】:2022-11-20 23:38:14
【问题描述】:

我正在使用 bs4 在 Python 中编写抓取工具,并希望从所有“a”标签中删除链接

我有html代码

html_code = '<a href="link">some text</a>'

我想删除 href="link" 并只获取

html_code = '<a>some text</a>'

我该怎么做?

【问题讨论】:

标签: python html web-scraping beautifulsoup


【解决方案1】:

我会按照以下方式进行

from bs4 import BeautifulSoup
html_code = '<a href="link">some text</a>'
soup = BeautifulSoup(html_code)
print("Before")
print(soup.prettify())
for node in soup.find_all("a"):
    node.attrs = {}
print("After")
print(soup.prettify())

给出输出

Before
<html>
 <body>
  <a href="link">
   some text
  </a>
 </body>
</html>
After
<html>
 <body>
  <a>
   some text
  </a>
 </body>
</html>

请注意,这将删除所有 &lt;a&gt; 标签的所有属性。

【讨论】:

    【解决方案2】:

    这能解决您的问题吗?

    html_code = html_code.replace(' href="link"','')
    

    输出:

    >>> print(html_code)
    
    >>> '<a>some text</a>'
    

    【讨论】:

      【解决方案3】:

      尝试:

      from bs4 import BeautifulSoup
      
      soup = BeautifulSoup('<a href="link">some text</a>', "html.parser")
      
      del soup.a.attrs
      print(soup.a)
      

      印刷:

      <a>some text</a>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-09
        • 2011-10-07
        • 2013-12-15
        • 2018-08-12
        • 2012-02-17
        • 1970-01-01
        • 2010-10-20
        相关资源
        最近更新 更多