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!
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With