Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace strings in HTML

From this HTML code:

<p class="description" dir="ltr">Name is a fine man. <br></p>

I'm looking for replacing "Name" using the following code:

target = soup.find_all(text="Name")
for v in target:
    v.replace_with('Id')

The output I would like to have is:

<p class="description" dir="ltr">Id is a fine man. <br></p>

When I:

print target
[]

Why doesn't it find the "Name"?

Thanks!

like image 421
Diego Avatar asked Jul 13 '26 21:07

Diego


1 Answers

The text node in your HTML contains some other text besides "Name". In this case, you need to relax search criteria to use contains instead of exact match, for example, by using regex. Then you can replace matched text nodes with the original text except for "Name" part should be replaced with "Id" by using simple string.replace() method, for example :

from bs4 import BeautifulSoup
import re

html = """<p class="description" dir="ltr">Name is a fine man. <br></p>"""
soup = BeautifulSoup(html)
target = soup.find_all(text=re.compile(r'Name'))
for v in target:
    v.replace_with(v.replace('Name','Id'))
print soup

output :

<html><body><p class="description" dir="ltr">Id is a fine man. <br/></p></body></html>
like image 120
har07 Avatar answered Jul 16 '26 16:07

har07



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!