1

I'm running a Python script which uses a value list as query parameters for an HTTP request over an API endpoint. Here a snap:


df = pd.read_excel('grp.xlsx', sheet_name='Sheet1', usecols="A")

for item in df.PLACE:
    df.PLACE.head()

    #1st level request
    def wbsearchentities_q(**kwargs):
        params = {
        'action': 'wbsearchentities',
        'format': 'json',
        'language': 'en',
        'search': item
    }        

        params.update(kwargs)

        response = requests.get(API_ENDPOINT, params=params)
        return response

    r = wbsearchentities_q(ids=item)
    item_id = (r.json()['search'][0]['id'])
    item_label = (r.json()['search'][0]['label'])    

I'm having this error: IndexError: list index out of range which means that some items from my list are not recognized by the API endpoint.

I would just pass over and continue the loop. I tried to fix using this without result.

Thanks in advance.

Pelide
  • 468
  • 1
  • 4
  • 19
  • Where do you get the error? – Aryerez Sep 25 '19 at 12:21
  • You need to wrap a `try/except` around your last 2 lines – EdChum Sep 25 '19 at 12:21
  • So, you just want to ignore the exception? cant see why `try\except` wont work, just wrap all of the loop code into `try\except`, also, what do you mean by no result? you keep getting the error even when you are wrapping the code with `try\except`? – Elad Cohen Sep 25 '19 at 12:22
  • As a note, you're losing a fair bit of performance re-defining your function at every iteration. Make `item` a positional arg and define the function outside of the loop – C.Nivs Sep 25 '19 at 12:24
  • check your response status code, `if r.status_code == 200` than take item id and label – kederrac Sep 25 '19 at 12:29
  • @Aryerez item_id = (r.json()['search'][0]['id']) – Pelide Sep 25 '19 at 12:31

2 Answers2

2

you can try:

for item in df.PLACE:
    try:
     ... your code ...
    except:
        pass
kederrac
  • 16,819
  • 6
  • 32
  • 55
2

In order to be specific only for that error (recommanded in order to avoid not handling other errors), and continue to the next item in the df:

try:
    item_id = (r.json()['search'][0]['id'])
    item_label = (r.json()['search'][0]['label'])
except IndexError:
    continue
Aryerez
  • 3,417
  • 2
  • 9
  • 17