Search code examples
pythonbeautifulsoupreplaceattributestags

I want to replace an html content with my own content


Below is the html code and I want to replace the content with " This is html code ". The code runs without errors but nothing changed and content remains same.

I want to replace "A full stack developer." with "This is html code"

soup='<meta content="A full stack developer." name="description"/>'

My code:

for i in soup.find_all("meta", "description"):

    var1=i.string
    var1.replace_with(var1.replace(var1, 'This is html code '))
    print(var1)
    
print(soup)

By the above method I am not getting error but the content attribute remains same.

I have tried different ways as well but I get this error:

'str' object has no attribute 'replace_with'

Can anyone guide me how to replace the content attribute with your own?


Solution

  • To access tag attribute, use [ ]:

    from bs4 import BeautifulSoup
    
    html_doc = '<meta content="A full stack developer." name="description" />'
    soup = BeautifulSoup(html_doc, "html.parser")
    
    # replace the attribute "content":
    soup.find("meta", {"name": "description"})["content"] = "This is html code"
    print(soup)
    

    Prints:

    <meta content="This is html code" name="description"/>