2

With beautifulsoup I get the html code of a site, let say it's this:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>

How I can add this line body {background-color:#b0c4de;} inside the head tag using beautifulsoup?

Lets say python code is:

#!/usr/bin/python

import cgi, cgitb, urllib2, sys
from bs4 import BeautifulSoup

site = "www.example.com"
page = urllib2.urlopen(site)
soup = BeautifulSoup(page)
2

1 Answer 1

10

You can use:

soup.head.append('body {background-color:#b0c4de;}')

But you should create a <style> tag before.

For instance:

head = soup.head
head.append(soup.new_tag('style', type='text/css'))
head.style.append('body {background-color:#b0c4de;}')
Sign up to request clarification or add additional context in comments.

1 Comment

AttributeError: 'NoneType' object has no attribute 'append'

Your Answer

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.