4

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>
3
  • I don't know the answer, but I'm guessing it involves BeautifulSoup :-) Commented Jun 11, 2014 at 7:47
  • @mgilson, won't a simple regex solve non-nested anchors case, will it? Commented Jun 11, 2014 at 7:49
  • stackoverflow.com/questions/2584885/strip-tags-python Commented Jun 11, 2014 at 7:52

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Looks like a perfect case for BeautifulSoup's unwrap() method:

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

This gives:

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

Comments

0

You can use Parser Library for it.. like BeautifulSoup and other also. I am not sure for it, but you can get something here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.