2024-05-14 04:07:29 发布
网友
如何在html(python)中将链接替换为锚?在
例如输入:
<p> Hello <a href="http://example.com">link text1</a> and <a href="http://example.com">link text2</a> ! </p>
我想要保存p标记的结果(只需删除标记):
你可以使用解析器库。。像美貌素和其他也一样。我不确定,但你可以买些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
这样可以得到:
您可以使用一个简单的regex和sub函数来完成此操作:
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>标记。在
<a..>
</a>
你可以使用解析器库。。像美貌素和其他也一样。我不确定,但你可以买些here
看起来是BeautifulSoup的^{} 方法的完美案例:
这样可以得到:
^{pr2}$您可以使用一个简单的regex和
sub
函数来完成此操作:此代码用空字符串替换所有出现的
<a..>
和</a>
标记。在相关问题 更多 >
编程相关推荐