Background: I want to download specific parts of users tweets (e.g. username, id, expanded url, etc) from the twitter api. I am able to do so successfully.
Problem: Because not all users have expanded_url
, I sometimes receive the following error:
IndexError: list index out of range
Goal: If such IndexError
occur, skip and proceed to collect new tweets
I think one way to solve this problem is by using a try/except statement
Questions: Is a try/except statement a valid way to do achieve this goal? If so, how do I properly apply a try/except statement?
I have tried the following:
class StdOutListener(StreamListener):
def on_data(self, data):
t = json.loads(data)
tweet_id = t['id_str']
user_name = t['user']['name']
try:
expanded_url = t['entities']['urls'][0]['expanded_url']
except:
pass
But I get the following error:
UnboundLocalError: local variable 'expanded_url' referenced before assignment
I have searched around SO, and have a few examples similar to my question (UnboundLocalError: local variable 'url_request' referenced before assignment, UnboundLocalError: local variable 'url' referenced before assignment)
But I'm not sure how to directly change my code so that I can implement the try/except statement. I am also open to other ways to solve this problem. Thank you!