0

I'm parsing an HTML file and searching for status of order in it. Sometimes, status doesn't exist, so BeautifulSoup returns NoneType, when I'm using it. To solve this problem I use if-else statement, but it doesn't work too. Python returns:

TypeError: object of type 'NoneType' has no len()

I am adding status to a dictionary, which contains other info from the order. The code below is a part, which adds new order's info to a dict.

database.append({
        "Title": title[0] + title.lower()[1:],
        "Name": name[0].upper() + name[1:],
        "Status": status.string[:len(status.string)-3] if status is not None else "Not listed",
        "Price": price
    })
felipsmartins
  • 13,269
  • 4
  • 48
  • 56
sailestim
  • 343
  • 1
  • 3
  • 11
  • Did you try inverting it? `"Not listed" if status is None else status.string[:len(status.string)-3]` I'm suspicious that python might be evaluating it anyway... – Idos Feb 15 '16 at 20:29
  • 3
    Are you sure you get error in _that_ code? http://ideone.com/N2U9Kl – Lol4t0 Feb 15 '16 at 20:31
  • Well I was wrong, non-reproducible it is then – Idos Feb 15 '16 at 20:33
  • also, `status.string[:-3] ` would do *exactly the same* as `status.string[:len(status.string)-3]` – Jasper Feb 15 '16 at 20:44
  • It seems that status `is not None`, but `status.string` is... – Jasper Feb 15 '16 at 20:48
  • @Jasper I've already tried this. In this case, Python says "NoneType has no string attribute" – sailestim Feb 15 '16 at 20:50
  • What did you try exactly? It seems that you have to handle three cases: status is None / status is not None, but status.string is / status and status.string are both not None. – Jasper Feb 15 '16 at 20:53
  • @Jasper if status.string is not None / if status is not None. Both solutions don't work for me. – sailestim Feb 15 '16 at 20:55

1 Answers1

1

There seem to be three cases:

  1. status is None
  2. status is not None, but status.string is
  3. both status and status.string are not None

You have to provide code that handles each case.

if status is not None and status.string is not None:
     st = status.string[:-3]
else:
     st = "Not listed"

database.append({
        "Title": title[0] + title.lower()[1:],
        "Name": name[0].upper() + name[1:],
        "Status": st,
        "Price": price
    })

You can also stick the whole if in the dict if you prefer. You could also use exceptions:

try:
     st = status.string[:-3]
except (TypeError, AttributeError):
     st = "Not listed"
Jasper
  • 3,939
  • 1
  • 18
  • 35