用文本替换HTML链接

2024-05-14 04:07:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在html(python)中将链接替换为锚?在

例如输入:

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

我想要保存p标记的结果(只需删除标记):

^{pr2}$

Tags: and标记comhttphello链接examplehtml
3条回答

你可以使用解析器库。。像美貌素和其他也一样。我不确定,但你可以买些here

看起来是BeautifulSoup的^{}方法的完美案例:

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

这样可以得到:

^{pr2}$

您可以使用一个简单的regex和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>标记。在

相关问题 更多 >