Python Tweepy – Getting the location of a user

In this article we will see how we can get the location of a user. The location of the user account need not be the exact physical location of the user. As the user is free to change their location, the location of the account can even by a hypothetical place. The location attribute is optional and is Nullable.

Identifying the location in the GUI :

In the above mentioned profile, India is the location of the profile.

In order to get the location we have to do the following :

  1. Identify the user ID or the screen name of the profile.
  2. Get the User object of the profile using the get_user() method with the user ID or the screen name.
  3. From this object, fetch the location attribute present in it.

Example 1: Consider the following profile :

We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058.



filter_none

edit
close

play_arrow

link
brightness_4
code

# import the module
import tweepy
  
# assign the values accordingly
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
  
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
  
# set access to user's access key and access secret 
auth.set_access_token(access_token, access_token_secret)
  
# calling the api 
api = tweepy.API(auth)
  
# the ID of the user
id = 57741058
  
# fetching the user
user = api.get_user(id)
  
# fetching the location
location = user.location
  
print("The location of the user is : " + location)

chevron_right


Output :

The location of the user is : India

Example 2: Consider the following profile :

We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG. Here the location is not mentioned.

filter_none

edit
close

play_arrow

link
brightness_4
code

# the screen name of the user
screen_name = "PracticeGfG"
  
# fetching the user
user = api.get_user(screen_name)
  
# fetching the name
name = user.name
  
if location == "":
    print("The user has not mentioned their loaction.")
else:
    print("The location of the user is : " + location)

chevron_right


Output :

The user has not mentioned their loaction.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.