26. Mining your own Facebook Account

We will have a look at how we can mine information like UsernameEmailLocationWebsite etc. from a user account automatically using a python script.
First let's have a look at the code:
#!usr/bin/env python
    # Program to mine data from your own facebook account
    
    import json
    import facebook
    
    def main():
    token = "{Your Token}"
    graph = facebook.GraphAPI(token)
    #fields = ['first_name', 'location{location}','email','link']
    profile = graph.get_object('me',fields='first_name,location,link,email')
    #return desired fields
    print(json.dumps(profile, indent=4))
    
    if __name__ == '__main__':
    main()
Here inside the main() method, we are trying to get the information about our own Facebook account. Let's try to understand the code line-by-line:
  • token: It is the access token required to access the page.
  • In the next line we created a GraphAPI object to access API methods.
  • Now, we have extracted the desired fields in a variable profile. Here, notice that 'me' in get_object() method indicates that we are doing it for our own account.
  • first_name: returns the first name of user.
  • location: The person's current location as entered by them on their profile. This field is not related to check-ins.
  • email: The person's primary email address listed on their profile. This field will not be returned if no valid email address is available.
  • link: A link to the person's timeline.
Besides these fields, there are numerous fields. For full list and description of fields refer the Facebook Graph API official documentation
Output:



The last line of the above code dumps the json format of information obtained in the variable profile.

Mining Data from a Facebook Page

Now, in this example we will be extracting data from the Facebook page of the 'God of Metal' band Metallica. To see the list of fields which can be extracted from a page refer here.
#!usr/bin/env python
    # Program to get a page information
    
    import json
    import facebook
    
    def main():
    token = "{Your Token}"
    graph = facebook.GraphAPI(token)
    page_name = raw_input("Enter a page name: ")
    
    # list of required fields
    fields = ['id','name','about','likes','link','band_members']
    
    fields = ','.join(fields)
    
    page = graph.get_object(page_name, fields=fields)
    
    print(json.dumps(page,indent=4))
    
    if __name__ == '__main__':
    main()

Output:



# Table of Contents:
28. Changing User Agent

# Ebooks for Network Programming with Python



logoblog

No comments:

Post a Comment