-3

I am brand new to python and coding in general. Can anyone understand why I am getting this IndexError?

Traceback (most recent call last):
  File "\\Mac\Home\Desktop\Python\Lab1\lab1_querystring.pageresults.addresssplit.headersadded.columnsadded.keysaddedtodictionary.py", line 54, in <module>
    city = splitaddress[1]
IndexError: list index out of range

The list I am trying to pull in each of my if statements/suites from has four items, but for some reason it keeps telling me the list index is out of range.

for listing in splititems:
    name = parse(listing,"itemprop=\"name\">","<").strip() # extract the business name

    # Try to extract the address into its constituent parts - street address, city, postal, see if you can put them into different columns in excel
    address = parse(listing,"<div class=\"ltext\" itemprop=\"address\" itemscope itemtype=\"http://schema.org/PostalAddress\">","</div>").strip() # extract the address
    splitaddress = address.split(',')

    streetaddress = splitaddress[0]
    city = splitaddress[1]
    postalcode = splitaddress[2]

    if len(splitaddress) >= 0:
            print splitaddress[0]

    if len(splitaddress) >= 1:
            print splitaddress[1]

    if len(splitaddress) >= 2:
            print splitaddress[2]

    phone = parse(listing,"itemprop=\"telephone\" content=\"","\"/>").strip() # extract the phone number

    print name, address, phone # take this out when you're finished your script - this is just for testing
    resultlist.append({'businessname':name,'streetaddress':streetaddress, 'city':city, 'postalcode':postalcode, 'phone':phone})
    del name,streetaddress,city,postalcode,phone
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • You should write code more. Try to take online courses or read some books about Python. – Greg Eremeev Mar 04 '17 at 06:47
  • Try to move the various `if len(splitaddress) >= 0` etc *before* you assign `city`. You'll see that `splitaddress` does not contain what you think it does. – Bakuriu Mar 04 '17 at 06:47
  • Looks like your `parse` function doesn't do what you're thinking it's doing... – Nir Alfasi Mar 04 '17 at 06:48
  • [What does your step debugger tell you?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) –  Mar 04 '17 at 06:49

1 Answers1

0

Your address does not contain commas but another separator:

In [1]: address = "Mr. Foo; Spam street 42; Eggsville"

In [2]: address.split(',')
Out[2]: ['Mr. Foo; Spam street 42; Eggsville']

If you were to assign this to splitaddress, everything except splitaddress[0] would raise an IndexError.

Check that len(splitaddress) > 1 before proceeding.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94