Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace HTML links with text

How to replace links with anchors in html (python)?

for example input:

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

i want at result with saved p tag (just a tag remove):

<p>
Hello link text1 and link text2 ! 
</p>
like image 894
Evg Avatar asked Oct 15 '25 17:10

Evg


1 Answers

You could do this with a simple regex and the sub function:

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>'

This code replaces all occuring <a..> and </a> tags with an empty string.

like image 106
miindlek Avatar answered Oct 18 '25 10:10

miindlek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!