Hello everybody!
This post will be about two new things: Using Python for getting Social Data and working with the LinkedIn API and is based on Matthew A. Russell´s book “Mining the Social Web“. If you are interested in that topic you should really take a look at this book.
The main feature of this API is getting contacts and this is what I will do in this tutorial. In the following tutorials I will show you then how to visualize you contacts. But for now we download our contacts.
API Key
First of all we have to get an API key. You can get it at https://www.linkedin.com/secure/developer
You have to login into your account and then on “Add New Application”.
There you have to give your new app a name and fill in some other details. For our purpose, as we don´t want to publish the app, you can write whatever you want. It is just important “r_basicprofile” in the section OAuth User Agreement.
Then just click on “Add Application” and you can see your app keys.
Download LinkedIn contacts with Python
Ok now we have our keys and can start with the Python part. You can use whatever Python IDE you want. I would recomment pyCharm as it works really great for me.
For downloading the contacts we use the linkedin-python package and for displaying them we use the prettytable package. Just open a terminal and type in:
1 2 |
pip install python-linkedin pip install prettytable |
Let´s take a look at the python code.
First of all we have to import the needed packages, set our LinkedIn app keys create create a so called “app” in the python code. This app will be our connection to the LinkedIn API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
CONSUMER_KEY = 'XXX' CONSUMER_SECRET = 'XXX' USER_TOKEN = 'XXX' USER_SECRET = 'XXX' auth = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,USER_TOKEN, USER_SECRET,RETURN_URL,permissions=linkedin.PERMISSIONS.enums.values()) app = linkedin.LinkedInApplication(auth)[/code] With the help of this app we can get our contacts with the get_connections() function. Then we store them in a JSON object. [code language="python"]import json connections = app.get_connections() linkedin_contacts = 'contacts.json' f = open(linkedin_contacts, 'w') f.write(json.dumps(connections, indent=1)) f.close() |
Then we can use the prettytable packe and print them as a nice looking table:
1 2 3 4 5 6 7 |
from prettytable import PrettyTable pt = PrettyTable(field_names=['Name', 'Location']) pt.align = 'l' [pt.add_row((c['firstName'] + ' ' + c['lastName'], c['location']['name'])) for c in connections['values'] if c.has_key('location')] print pt |