Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting into a html file using python

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?

like image 898
richie Avatar asked Oct 01 '13 18:10

richie


1 Answers

Use BeautifulSoup. Here's an example there 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:

  • Add parent tags with beautiful soup
  • How to append a tag after a link with BeautifulSoup
like image 67
alecxe Avatar answered Sep 19 '22 23:09

alecxe