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.
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:
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.
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')
Then we can use the prettytable packe and print them as a nice looking table:
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']