Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8834907
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T09:08:06+00:00 2026-06-14T09:08:06+00:00

I’m writing a script that extracts the content out of an article and removes

  • 0

I’m writing a script that extracts the content out of an article and removes any unnecessary stuff eg. scripts and styling. Beautiful Soup keeps raising the following exception:

'<class 'bs4.element.Tag'>' object has no attribute 'contents'

Here’s the code of the trim function (element is the HTML element that contains the content of the webpage):

def trim(element):
    elements_to_remove = ('script', 'style', 'link', 'form', 'object', 'iframe')
    for i in elements_to_remove:
        remove_all_elements(element, i)

    attributes_to_remove = ('class', 'id', 'style')
    for i in attributes_to_remove:
        remove_all_attributes(element, i)

    remove_all_comments(element)

    # Remove divs that have more non-p elements than p elements
    for div in element.find_all('div'):
        p = len(div.find_all('p'))
        img = len(div.find_all('img'))
        li = len(div.find_all('li'))
        a = len(div.find_all('a'))

        if p == 0 or img > p or li > p or a > p:
            div.decompose()

Looking at the stack trace, the problem seems to be coming from this method right after the for statement:

    # Remove divs that have more non-p elements than p elements
    for div in element.find_all('div'):
        p = len(div.find_all('p')) # <-- div.find_all('p')

I don’t get why this instance of bs4.element.Tag doesn’t have the attribute ‘contents’? I tried it out on an actual webpage and the element was full of p’s and img’s…

Here’s the traceback (This is part of a Django project I’m working on):

Environment:


Request Method: POST
Request URL: http://localhost:8000/read/add/

Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'home',
 'account',
 'read',
 'review')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/home/marco/.virtualenvs/sandra/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/marco/sandra/read/views.py" in add
  24.             Article.objects.create_article(request.user, url)
File "/home/marco/sandra/read/models.py" in create_article
  11.         title, content = logic.process_html(web_page.read())
File "/home/marco/sandra/read/logic.py" in process_html
  7.     soup = htmlbarber.give_haircut(BeautifulSoup(html_code, 'html5lib'))
File "/home/marco/sandra/read/htmlbarber/__init__.py" in give_haircut
  45.     scissor.trim(element)
File "/home/marco/sandra/read/htmlbarber/scissor.py" in trim
  35.         p = len(div.find_all('p'))
File "/home/marco/.virtualenvs/sandra/local/lib/python2.7/site-packages/bs4/element.py" in find_all
  1128.         return self._find_all(name, attrs, text, limit, generator, **kwargs)
File "/home/marco/.virtualenvs/sandra/local/lib/python2.7/site-packages/bs4/element.py" in _find_all
  413.                 return [element for element in generator
File "/home/marco/.virtualenvs/sandra/local/lib/python2.7/site-packages/bs4/element.py" in descendants
  1140.         if not len(self.contents):
File "/home/marco/.virtualenvs/sandra/local/lib/python2.7/site-packages/bs4/element.py" in __getattr__
  924.             "'%s' object has no attribute '%s'" % (self.__class__, tag))

Exception Type: AttributeError at /read/add/
Exception Value: '<class 'bs4.element.Tag'>' object has no attribute 'contents'

Here’s the source code of remove_all_* functions:

def remove_all_elements(element_to_clean, unwanted_element_name):
    for to_remove in element_to_clean.find_all(unwanted_element_name):
        to_remove.decompose()

def remove_all_attributes(element_to_clean, unwanted_attribute_name):
    for to_inspect in [element_to_clean] + element_to_clean.find_all():
        try:
            del to_inspect[unwanted_attribute_name]
        except KeyError:
            pass

def remove_all_comments(element_to_clean):
    for comment in element_to_clean.find_all(text=lambda text:isinstance(text, Comment)):
        comment.extract()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T09:08:07+00:00Added an answer on June 14, 2026 at 9:08 am

    I think the problem is that in remove_all_elements or somewhere else in your code you are deleting the contents attribute of some of your tags.

    It looks like this is happening when you call to_remove.decompose(). Here is the source for that method:

    def decompose(self):
        """Recursively destroys the contents of this tree."""
        self.extract()
        i = self
        while i is not None:
            next = i.next_element
            i.__dict__.clear()
            i = next
    

    Here is what happens if you call this function manually:

    >> soup = BeautifulSoup('<div><p>hi</p></div>')
    >>> d0 = soup.find_all('div')[0]
    >>> d0
    <div><p>hi</p></div>
    >>> d0.decompose()
    >>> d0
    Traceback (most recent call last):
    ...
    Traceback (most recent call last):
    AttributeError: '<class 'bs4.element.Tag'>' object has no attribute 'contents'
    

    It appears that once you have called decompose on a tag you must never attempt to use that tag again. I’m not quite sure where this is happening though.

    One thing I would try checking is that len(element.__dict__) > 0 at all times in your trim() function.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a small JavaScript validation script that validates inputs based on Regex. I
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I have an autohotkey script which looks up a word in a bilingual dictionary

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.