how to test attribute existence of feedparser objects

H

HansPeter

Hi,

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

File "build\bdist.win32\egg\feedparser.py", 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])
try:
print "TITLE ",d.feed.title
except:
print "HAS NO TITLE"
wc={}

Regards HansPeter
 
C

Chris Rebert

Hi,

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

 File "build\bdist.win32\egg\feedparser.py", 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.

hasattr(obj, attr_name)
See docs.python.org/dev/library/functions.html#hasattr

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.

Cheers,
Chris
 
X

xDog Walker

Hi,

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

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

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

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¶
60
 
S

Steven D'Aprano

Use standard Python dictionary functions such as has_key to test whether
an element exists.

Idiomatic Python code today no longer uses has_key.

# Was:
d.feed.has_key('title')

# Now preferred
'title' in d.feed
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top