7

I have a html file where I would like to insert a <meta> tag between the <head> & </head> tags using python. If I open the file in append mode how do I get to the relevant position where the <meta> tag is to be inserted?

alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
asked Oct 1, 2013 at 18:23
1
  • 6
    What you describe isn't appending, it is inserting (as you yourself state). Append mode allows you to add to the end of the file, and thus won't help here. Commented Oct 1, 2013 at 18:26

1 Answer 1

21

Use BeautifulSoup. Here's an example where a meta tag is inserted right after the title tag using insert_after():

from bs4 import BeautifulSoup as Soup
html = """
<html>
<head>
<title>Test Page</title>
</head>
<body>
<div>test</div>
</html>
"""
soup = Soup(html)
title = soup.find('title')
meta = soup.new_tag('meta')
meta['content'] = "text/html; charset=UTF-8"
meta['http-equiv'] = "Content-Type"
title.insert_after(meta)
print soup

prints:

<html>
 <head>
 <title>Test Page</title>
 <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
 </head>
 <body>
 <div>test</div>
 </body>
</html>

You can also find head tag and use insert() with a specified position:

head = soup.find('head')
head.insert(1, meta)

Also see:

Trenton McKinney
63.2k41 gold badges170 silver badges213 bronze badges
answered Oct 1, 2013 at 18:37
Sign up to request clarification or add additional context in comments.

1 Comment

One way to do it: with open("/file/name.html", "r") soup = Soup(file) title = soup.find('title') meta = soup.new_tag('meta') meta['content'] = "text/html; charset=UTF-8" meta['http-equiv'] = "Content-Type" title.insert_after(meta) with open("/file/name.html", "w") as f: f.write(str(soup)) It worked for me, thanks.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.