用文本替换HTML链接

4 投票
3 回答
5013 浏览
提问于 2025-04-18 09:23

如何在HTML中用锚点替换链接(用Python)?

比如说,输入是:

 <p> Hello <a href="http://example.com">link text1</a> and <a href="http://example.com">link text2</a> ! </p>

我想要的结果是保留p标签(只去掉链接标签):

<p>
Hello link text1 and link text2 ! 
</p>

3 个回答

0

你可以使用解析库来实现这个功能,比如BeautifulSoup等。我不太确定具体情况,但你可以在这里找到一些相关的信息。

3

这看起来是使用BeautifulSoup的 unwrap() 方法的一个完美例子:

from bs4 import BeautifulSoup
data = '''<p> Hello <a href="http://example.com">link text1</a> and <a href="http://example.com">link text2</a> ! </p>'''
soup = BeautifulSoup(data)
p_tag = soup.find('p')
for _ in p_tag.find_all('a'):
    p_tag.a.unwrap()
print p_tag

这样可以得到:

<p> Hello link text1 and link text2 ! </p>
5

你可以用一个简单的正则表达式和 sub 函数来实现这个功能:

import re

text = '<p> Hello <a href="http://example.com">link text1</a> and <a href="http://example.com">link text2</a> ! </p>'
pattern =r'<(a|/a).*?>'

result = re.sub(pattern , "", text)

print result
'<p> Hello link text1 and link text2 ! </p>'

这段代码会把所有出现的 <a..></a> 标签替换成空字符串,也就是说把它们删除掉。

撰写回答