跳转到主要内容

LinkedIn API的Python接口

项目描述

LinkedIn Build Status

Python接口到LinkedIn API

此库提供了一个纯Python接口,用于LinkedIn的 ProfileGroupCompanyJobsSearchShareNetworkInvitation REST API。

LinkedIn 提供了一项服务,允许人们通过基于OAuth的API将他们的LinkedIn个人资料和网络带到您的网站或应用程序。此库提供了一个轻量级接口,在复杂的基于OAuth的LinkedIn API之上,使Python程序员更容易使用。

致谢

维护者: Jonathan Dekhtiar

贡献者:* Ozgur Vatansever * Marshall Lusher * Jonathan Dekhtiar * Abraham Williams * Matthew A. Russell * Samuel Marks * Emlyn Clay * Ivan Kravets * Devin Barry * Josh Owen * Chengxin Cai * Yuri Prezument * Jay Zeng * Julien Muniak * John Franey * Adrian Sgn * Luca Adalberto Vandro * Jack * Scotty Delta * Michael Blakeley * Song Zhen-Gang * Ismail Coskuner * Marshyang * Iurii Kudriavtsev * Kartik Ayyar * Kit Sunde * Patrick Müssig

安装

可在Python包索引中找到:https://pypi.python.org/pypi/python3-linkedin

pip install python3-linkedin

如果需要,可以使用以下命令编译库

## First clone the repository
git clone https://github.com/DEKHTIARJonathan/python3-linkedin.git

## Then install the library
python setup.py install

身份验证

LinkedIn REST API现在支持用于身份验证的OAuth 2.0协议。此包提供了连接到LinkedIn的完整OAuth 2.0实现,以及使用OAuth 1.0a流程的选项,这对于开发目的或仅访问您自己的数据可能很有帮助。

HTTP API示例

请在新应用的LinkedIn开发者控制台上声明和设置

设置LINKEDIN_API_KEYLINKEDIN_API_SECRET,将您的应用配置为重定向到http://localhost:8080/code,然后执行

  1. http_api.py

  2. 在浏览器中访问http://localhost:8080,使用curl或类似工具

  3. 浏览器将打开一个标签页,在那里给予LinkedIn权限

  4. 您将看到可用的路由列表,点击任何一项,例如

  5. curl -XGET http://localhost:8080/get_profile

开发者身份验证

要作为开发者连接到LinkedIn或仅访问您自己的数据,您甚至不需要实现涉及重定向的OAuth 2.0流程。您只需使用LinkedIn应用程序提供的4个凭据作为OAuth 1.0a流程的一部分,即可立即访问您的数据。以下是方法

from linkedin import linkedin

# Define CONSUMER_KEY, CONSUMER_SECRET,
# USER_TOKEN, and USER_SECRET from the credentials
# provided in your LinkedIn application

# Instantiate the developer authentication class

authentication = linkedin.LinkedInDeveloperAuthentication(
                    CONSUMER_KEY,
                    CONSUMER_SECRET,
                    USER_TOKEN,
                    USER_SECRET,
                    RETURN_URL,
                    linkedin.PERMISSIONS.enums.values()
                )

# Optionally one can send custom "state" value that will be returned from OAuth server
# It can be used to track your user state or something else (it's up to you)
# Be aware that this value is sent to OAuth server AS IS - make sure to encode or hash it

# authorization.state = 'your_encoded_message'

# Pass it in to the app...

application = linkedin.LinkedInApplication(authentication)

# Use the app....

application.get_profile()

生产身份验证

为了使用LinkedIn OAuth 2.0,您需要从LinkedIn开发者控制台获取以下两个密钥

APPLICATON_KEY    = '##############'
APPLICATON_SECRET = '################'

您可以从这里了解更多关于Oauth2身份验证过程的信息。

在授予应用访问权限(提供适当的权限)后,LinkedIn会将用户重定向回您网站的URL。我们称该URL为返回URL。假设您的返回URL是https://localhost:8000,您可以编写如下内容

from linkedin import linkedin

APPLICATON_KEY    = '##############'
APPLICATON_SECRET = '################'

RETURN_URL = 'http://localhost:8000'

authentication = linkedin.LinkedInAuthentication(
                    APPLICATON_KEY,
                    APPLICATON_SECRET,
                    RETURN_URL,
                    linkedin.PERMISSIONS.enums.values()
                )

# Optionally one can send custom "state" value that will be returned from OAuth server
# It can be used to track your user state or something else (it's up to you)
# Be aware that this value is sent to OAuth server AS IS - make sure to encode or hash it
#authorization.state = 'your_encoded_message'

print (authentication.authorization_url)  # open this url on your browser

授予应用访问权限后,您将被重定向到返回URL,并在您的RETURN_URL后面附加以下查询字符串

"http://localhost:8000/?code=#############################################&state=########################"

此URL包含授权码的值。在手动设置后,我们可以调用.get_access_token()来获取实际令牌。

from linkedin import linkedin

APPLICATON_KEY    = '##############'
APPLICATON_SECRET = '################'

RETURN_URL = 'http://localhost:8000'

authentication = linkedin.LinkedInAuthentication(
                    APPLICATON_KEY,
                    APPLICATON_SECRET,
                    RETURN_URL,
                    linkedin.PERMISSIONS.enums.values()
                )

authentication.authorization_code = '#############################################'
result = authentication.get_access_token()

print ("Access Token:", result.access_token)
print ("Expires in (seconds):", result.expires_in)

获取访问令牌后,您现在可以代表授予您应用程序访问权限的用户进行API调用。此外,为了避免在连续请求中每次都通过OAuth流程,可以将之前获得的访问令牌直接分配给应用程序实例。

from linkedin import linkedin

application = linkedin.LinkedInApplication(token='###################################')

Python解释器快速使用

对于使用解释器测试库,您可以受益于测试服务器。

from linkedin import server
application = server.quick_api(KEY, SECRET)

这将打印授权URL到屏幕上。使用浏览器进入该URL以授权应用程序。完成后,该方法将返回一个您现在可以使用的API对象。

个人资料API

个人资料API返回成员的LinkedIn个人资料。您可以使用此调用返回用户个人资料的两种版本,即公开个人资料标准个人资料。更多信息,请参阅文档

application.get_profile()
{u'firstName': u'ozgur',
 u'headline': u'This is my headline',
 u'lastName': u'vatansever',
 u'siteStandardProfileRequest': {u'url': u'https://www.linkedin.com/profile/view?id=46113651&authType=name&authToken=Egbj&trk=api*a101945*s101945*'}}

有许多字段选择器使客户端能够从API获取更多信息。每个API使用的所有它们都列在这里

application.get_profile(selectors=['id', 'first-name', 'last-name', 'location', 'distance', 'num-connections', 'skills', 'educations'])
{u'distance': 0,
 u'educations': {u'_total': 1,
  u'values': [{u'activities': u'This is my activity and society field',
    u'degree': u'graduate',
    u'endDate': {u'year': 2009},
    u'fieldOfStudy': u'computer science',
    u'id': 42611838,
    u'notes': u'This is my additional notes field',
    u'schoolName': u'\u0130stanbul Bilgi \xdcniversitesi',
    u'startDate': {u'year': 2004}}]},
 u'firstName': u'ozgur',
 u'id': u'COjFALsKDP',
 u'lastName': u'vatansever',
 u'location': {u'country': {u'code': u'tr'}, u'name': u'Istanbul, Turkey'},
 u'numConnections': 13}

联系人API

联系人API返回已授权其账户访问权限的用户的第一级联系人列表。更多信息,请参阅其文档

要获取您的联系人,只需调用带有适当GET查询字符串的.get_connections()方法。

application.get_connections()
{u'_total': 13,
 u'values': [{u'apiStandardProfileRequest': {u'headers': {u'_total': 1,
     u'values': [{u'name': u'x-li-auth-token', u'value': u'name:16V1033'}]},
    u'url': u'https://api.linkedin.com/v1/people/lddvGtD5xk'},
   u'firstName': u'John',
   u'headline': u'Ruby',
   u'id': u'2323SDFSsfd34',
   u'industry': u'Computer Software',
   u'lastName': u'DOE',
   u'location': {u'country': {u'code': u'tr'}, u'name': u'Istanbul, Turkey'},
   u'siteStandardProfileRequest': {u'url': u'https://www.linkedin.com/profile/view?id=049430532&authType=name&authToken=16V8&trk=api*a101945*s101945*'}},
   ....

application.get_connections(selectors=['headline', 'first-name', 'last-name'], params={'start':10, 'count':5})

搜索API

有3种类型的搜索API。第一种是人员搜索API,第二种是公司搜索API,最后一种是工作搜索API

人员搜索API返回有关人员的信息。它允许您实现当您在LinkedIn.com右上角框中搜索“人员”时显示的大部分内容。更多信息请参阅这里

application.search_profile(selectors=[{'people': ['first-name', 'last-name']}], params={'keywords': 'apple microsoft'})
# Search URL is https://api.linkedin.com/v1/people-search:(people:(first-name,last-name))?keywords=apple%20microsoft

{u'people': {u'_count': 10,
  u'_start': 0,
  u'_total': 2,
  u'values': [
   {u'firstName': u'John', u'lastName': 'Doe'},
   {u'firstName': u'Jane', u'lastName': u'Doe'}
  ]}}

公司搜索API允许跨公司页面搜索。更多信息请参阅这里

application.search_company(selectors=[{'companies': ['name', 'universal-name', 'website-url']}], params={'keywords': 'apple microsoft'})
# Search URL is https://api.linkedin.com/v1/company-search:(companies:(name,universal-name,website-url))?keywords=apple%20microsoft

{u'companies': {u'_count': 10,
  u'_start': 0,
  u'_total': 1064,
  u'values': [{u'name': u'Netflix',
    u'universalName': u'netflix',
    u'websiteUrl': u'httsp://netflix.com'},
   {u'name': u'Alliance Data',
    u'universalName': u'alliance-data',
    u'websiteUrl': u'www.alliancedata.com'},
   {u'name': u'GHA Technologies',
    u'universalName': u'gha-technologies',
    u'websiteUrl': u'www.gha-associates.com'},
   {u'name': u'Intelligent Decisions',
    u'universalName': u'intelligent-decisions',
    u'websiteUrl': u'https://www.intelligent.net'},
   {u'name': u'Mindfire Solutions',
    u'universalName': u'mindfire-solutions',
    u'websiteUrl': u'www.mindfiresolutions.com'},
   {u'name': u'Babel Media',
    u'universalName': u'babel-media',
    u'websiteUrl': u'https://www.babelmedia.com/'},
   {u'name': u'Milestone Technologies',
    u'universalName': u'milestone-technologies',
    u'websiteUrl': u'www.milestonepowered.com'},
   {u'name': u'Denali Advanced Integration',
    u'universalName': u'denali-advanced-integration',
    u'websiteUrl': u'www.denaliai.com'},
   {u'name': u'MicroAge',
    u'universalName': u'microage',
    u'websiteUrl': u'www.microage.com'},
   {u'name': u'TRUSTe',
    u'universalName': u'truste',
    u'websiteUrl': u'https://www.truste.com/'}]}}

工作搜索API允许在LinkedIn的工作帖子中进行搜索。更多信息请参阅这里

application.search_job(selectors=[{'jobs': ['id', 'customer-job-code', 'posting-date']}], params={'title': 'python', 'count': 2})
{u'jobs': {u'_count': 2,
  u'_start': 0,
  u'_total': 206747,
  u'values': [{u'customerJobCode': u'0006YT23WQ',
    u'id': 5174636,
    u'postingDate': {u'day': 21, u'month': 3, u'year': 2013}},
   {u'customerJobCode': u'00023CCVC2',
    u'id': 5174634,
    u'postingDate': {u'day': 21, u'month': 3, u'year': 2013}}]}}

群组API

群组API提供丰富的读取和与LinkedIn群组功能交互的访问权限。更多信息请参阅这里。通过该接口,您可以获取群组详细信息、获取您的群组成员资格以及您作为成员的特定群组的帖子。

application.get_group(41001)
{u'id': u'41001', u'name': u'Object Oriented Programming'}

application.get_memberships(params={'count': 20})
{u'_total': 1,
 u'values': [{u'_key': u'25827',
   u'group': {u'id': u'25827', u'name': u'Python Community'},
   u'membershipState': {u'code': u'member'}}]}

application.get_posts(41001)

application.get_post_comments(
    %POST_ID%,
    selectors=[
        {"creator": ["first-name", "last-name"]},
        "creation-timestamp",
        "text"
    ],
    params={"start": 0, "count": 20}
)

您还可以向特定群组提交新帖子。

title = 'Scala for the Impatient'
summary = 'A new book has been published'
submitted_url = 'https://horstmann.com/scala/'
submitted_image_url = 'https://horstmann.com/scala/images/cover.png'
description = 'It is a great book for the keen beginners. Check it out!'

application.submit_group_post(41001, title, summary, submitted_url, submitted_image_url, description)

公司API

公司API:* 根据公司ID或通用名称检索并显示一个或多个公司简介。* 返回基本公司简介数据,例如名称、网站和行业。* 返回对其他公司内容的引用,例如RSS流和Twitter源。

您可以使用其ID通用名称查询公司。更多信息,请参阅这里

application.get_companies(company_ids=[1035], universal_names=['apple'], selectors=['name'], params={'is-company-admin': 'true'})
# 1035 is Microsoft
# The URL is as follows: https://api.linkedin.com/v1/companies::(1035,universal-name=apple)?is-company-admin=true

{u'_total': 2,
 u'values': [{u'_key': u'1035', u'name': u'Microsoft'},
  {u'_key': u'universal-name=apple', u'name': u'Apple'}]}

# Get the latest updates about Microsoft
application.get_company_updates(1035, params={'count': 2})
{u'_count': 2,
 u'_start': 0,
 u'_total': 58,
 u'values': [{u'isCommentable': True,
   u'isLikable': True,
   u'isLiked': False,
   u'numLikes': 0,
   u'timestamp': 1363855486620,
   u'updateComments': {u'_total': 0},
   u'updateContent': {u'company': {u'id': 1035, u'name': u'Microsoft'},
    u'companyJobUpdate': {u'action': {u'code': u'created'},
     u'job': {u'company': {u'id': 1035, u'name': u'Microsoft'},
      u'description': u'Job Category: SalesLocation: Sacramento, CA, USJob ID: 812346-106756Division: Retail StoresStore...',
      u'id': 5173319,
      u'locationDescription': u'Sacramento, CA, US',
      u'position': {u'title': u'Store Manager, Specialty Store'},
      u'siteJobRequest': {u'url': u'https://www.linkedin.com/jobs?viewJob=&jobId=5173319'}}}},
   u'updateKey': u'UNIU-c1035-5720424522989961216-FOLLOW_CMPY',
   u'updateType': u'CMPY'},
  {u'isCommentable': True,
   u'isLikable': True,
   u'isLiked': False,
   u'numLikes': 0,
   u'timestamp': 1363855486617,
   u'updateComments': {u'_total': 0},
   u'updateContent': {u'company': {u'id': 1035, u'name': u'Microsoft'},
    u'companyJobUpdate': {u'action': {u'code': u'created'},
     u'job': {u'company': {u'id': 1035, u'name': u'Microsoft'},
      u'description': u'Job Category: Software Engineering: TestLocation: Redmond, WA, USJob ID: 794953-81760Division:...',
      u'id': 5173313,
      u'locationDescription': u'Redmond, WA, US',
      u'position': {u'title': u'Software Development Engineer in Test, Senior-IEB-MSCIS (794953)'},
      u'siteJobRequest': {u'url': u'https://www.linkedin.com/jobs?viewJob=&jobId=5173313'}}}},
   u'updateKey': u'UNIU-c1035-5720424522977378304-FOLLOW_CMPY',
   u'updateType': u'CMPY'}]}

您还可以关注或取消关注特定公司。

application.follow_company(1035)
True

application.unfollow_company(1035)
True

工作API

工作API提供查看工作和工作数据的访问权限。更多信息请参阅其文档

application.get_job(job_id=5174636)
{u'active': True,
 u'company': {u'id': 2329, u'name': u'Schneider Electric'},
 u'descriptionSnippet': u"The Industrial Accounts Sales Manager is a quota carrying senior sales position principally responsible for generating new sales and growing company's share of wallet within the industrial business, contracting business and consulting engineering business. The primary objective is to build and establish strong and lasting relationships with technical teams and at executive level within specific in",
 u'id': 5174636,
 u'position': {u'title': u'Industrial Accounts Sales Manager'},
 u'postingTimestamp': 1363860033000}

您还可以获取您的工作书签。

application.get_job_bookmarks()
{u'_total': 0}

分享API

网络更新是LinkedIn的核心体验之一,使用户能够将丰富的内容分享到他们的专业网络。更多信息请参阅这里

application.submit_share('Posting from the API using JSON', 'A title for your share', None, 'https://www.linkedin.com', 'https://d.pr/3OWS')
{'updateKey': u'UNIU-8219502-5705061301949063168-SHARE'
 'updateURL': 'https://www.linkedin.com/updates?discuss=&scope=8219502&stype=M&topic=5705061301949063168&type=U&a=aovi'}

网络API

获取网络更新 API 返回用户网络更新,这是领英对用户动态的称呼。此调用返回了 LinkedIn.com 首页中间栏显示的大部分内容,无论是成员的个人动态还是成员的联系人的动态。您可以在此处获取更多信息:这里

有许多网络更新类型。您可以通过导入 NETWORK_UPDATES 枚举来查看它们。

from linkedin.linkedin import NETWORK_UPDATES
print NETWORK_UPDATES.enums
{'APPLICATION': 'APPS',
 'CHANGED_PROFILE': 'PRFU',
 'COMPANY': 'CMPY',
 'CONNECTION': 'CONN',
 'EXTENDED_PROFILE': 'PRFX',
 'GROUP': 'JGRP',
 'JOB': 'JOBS',
 'PICTURE': 'PICT',
 'SHARED': 'SHAR',
 'VIRAL': 'VIRL'}

update_types = (NETWORK_UPDATES.CONNECTION, NETWORK_UPDATES.PICTURE)
application.get_network_updates(update_types)

{u'_total': 1,
 u'values': [{u'isCommentable': True,
   u'isLikable': True,
   u'isLiked': False,
   u'numLikes': 0,
   u'timestamp': 1363470126509,
   u'updateComments': {u'_total': 0},
   u'updateContent': {u'person': {u'apiStandardProfileRequest': {u'headers': {u'_total': 1,
       u'values': [{u'name': u'x-li-auth-token', u'value': u'name:Egbj'}]},
      u'url': u'https://api.linkedin.com/v1/people/COjFALsKDP'},
     u'firstName': u'ozgur',
     u'headline': u'This is my headline',
     u'id': u'COjFALsKDP',
     u'lastName': u'vatansever',
     u'siteStandardProfileRequest': {u'url': u'https://www.linkedin.com/profile/view?id=46113651&authType=name&authToken=Egbj&trk=api*a101945*s101945*'}}},
   u'updateKey': u'UNIU-46113651-5718808205493026816-SHARE',
   u'updateType': u'SHAR'}]}

邀请 API

邀请 API 允许您的用户邀请他们在您的应用程序中找到的人加入他们的 LinkedIn 网络。您可以在此处获取更多信息:这里

from linkedin.models import LinkedInRecipient, LinkedInInvitation
recipient = LinkedInRecipient(None, 'john.doe@python.org', 'John', 'Doe')
print recipient.json
{'person': {'_path': '/people/email=john.doe@python.org',
  'first-name': 'John',
  'last-name': 'Doe'}}

invitation = LinkedInInvitation('Hello John', "What's up? Can I add you as a friend?", (recipient,), 'friend')
print invitation.json
{'body': "What's up? Can I add you as a friend?",
 'item-content': {'invitation-request': {'connect-type': 'friend'}},
 'recipients': {'values': [{'person': {'_path': '/people/email=john.doe@python.org',
     'first-name': 'John',
     'last-name': 'Doe'}}]},
 'subject': 'Hello John'}

application.send_invitation(invitation)
True

节流限制

LinkedIn API 密钥默认情况下是节流的。您应该查看 节流限制文档 以获取更多信息。

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分布

python3-linkedin-1.0.2.tar.gz (23.8 kB 查看哈希值)

上传时间

构建分布

python3_linkedin-1.0.2-py3-none-any.whl (25.0 kB 查看哈希值)

上传时间 Python 3

python3_linkedin-1.0.2-py2.py3-none-any.whl (25.0 kB 查看哈希值)

上传时间 Python 2 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面