views:

24

answers:

2

I am looping through table rows in a table, but the first 1 or 2 rows doesn't have the elements I am looking for (they are for table column headers etc.).

So after say the 3rd table row, there are elements in the table cells (td) that have what I am looking for.

e.g.

td[0].a.img['src']

But calling this fails since the first few rows don't have this.

How can I guard against these cases so my script doesn't fail?

I get errors like:

nonetype object is unsubscriptable
+1  A: 

Starting from tr:

for td in tr.findChildren('td'):
    img = td.findChild('img')
    if img:
        src = img.get('src', '')  # return a blank string if there's no src attribute
        if src:
            # do something with src
ars
+1  A: 

Simplest and clearest, if you want your code "in line":

theimage = td[0].a.img
if theimage is not None:
   use(theimage['src'])

Or, preferably, wrap the None check in a tiny function of your own, e.g.:

def getsrc(image):
  return None if image is None else image['src']

and use getsrc(td[0].a.img).

Alex Martelli