how to test attribute existence of feedparser objects

Discussion in 'Python' started by HansPeter, Dec 8, 2011.

  1. HansPeter

    HansPeter Guest


    While using the feedparser library for downloading RSS feeds some of
    the blog entries seem to have no title.

    File "build\bdist.win32\egg\", line 382, in __getattr__
    AttributeError: object has no attribute 'title'

    Is there a way to test the existence of an attribute?

    I can use an exception but like below to see whether it exists but
    this is a clumsy way since the function has to return the title.

    d=feedparser.parse(url,handlers = [proxy])
    print "TITLE ",d.feed.title
    print "HAS NO TITLE"

    Regards HansPeter
    HansPeter, Dec 8, 2011
    1. Advertisements

  2. HansPeter

    Chris Rebert Guest

    hasattr(obj, attr_name)

    That said, sounds like it won't make much difference in the particular
    case you mention.
    Also, never use a bare "except:" clause, unless you know what you're
    doing and have a really good reason. Do "except AttributeError" in
    this case.

    Chris Rebert, Dec 8, 2011
    1. Advertisements

  3. HansPeter

    xDog Walker Guest

    From the Fine Manual for feedparser 5.1:

    Testing for Existence¶

    Feeds in the real world may be missing elements, even elements that are
    required by the specification. You should always test for the existence of an
    element before getting its value. Never assume an element is present.

    Use standard Python dictionary functions such as has_key to test whether an
    element exists.
    Testing if elements are present¶
    xDog Walker, Dec 10, 2011
  4. Idiomatic Python code today no longer uses has_key.

    # Was:

    # Now preferred
    'title' in d.feed
    Steven D'Aprano, Dec 10, 2011
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.