LinkedIn API Python密钥错误2.7

时间:2013-04-14 14:07:41

标签: python json csv

此代码可在线获取,以在Linkedin中运行您的连接地图 这使用了linkedin api。 我能够连接正常,一切运行正常,直到实际将数据写入csv的最后一个脚本。

每当我运行代码

import oauth2 as oauth
import urlparse
import simplejson
import codecs

CONSUMER_KEY = "xxx"
CONSUMER_SECRET = "xxx"
OAUTH_TOKEN = "xxx"
OAUTH_TOKEN_SECRET = "xxx"

OUTPUT = "linked.csv"

def linkedin_connections():

    # Use your credentials to build the oauth client
consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
token = oauth.Token(key=OAUTH_TOKEN, secret=OAUTH_TOKEN_SECRET)
client = oauth.Client(consumer, token)

# Fetch first degree connections
resp, content = client.request('http://api.linkedin.com/v1/people/~/connections?format=json')
results = simplejson.loads(content)    

# File that will store the results
output = codecs.open(OUTPUT, 'w', 'utf-8')

# Loop thru the 1st degree connection and see how they connect to each other
for result in results["values"]:
    con = "%s %s" % (result["firstName"].replace(",", " "),    result["lastName"].replace(",", " "))
    print >>output, "%s,%s" % ("John Henry",  con)

# This is the trick, use the search API to get related connections
    u = "https://api.linkedin.com/v1/people/%s:(relation-to-viewer:(related-connections))?format=json" % result["id"]
    resp, content = client.request(u)
    rels = simplejson.loads(content)
try:
for rel in rels['relationToViewer']['relatedConnections']['values']:
    sec = "%s %s" % (rel["firstName"].replace(",", " "), rel["lastName"].replace(",", " "))
    print >>output, "%s,%s" % (con, sec)
except:
    pass

if __name__ == '__main__':
    linkedin_connections()     

for result in results["values"]:
    KeyError: 'values'

当我运行时,我收到一条错误消息:

Traceback (most recent call last):

File "linkedin-2-query.py", line 51, in <module>
linkedin_connections()
File "linkedin-2-query.py", line 35, in linkedin_connections
for result in results["values"]:
KeyError: 'values'

非常感谢任何建议或帮助!

1 个答案:

答案 0 :(得分:0)

我在帖子Visualizing your LinkedIn graph using Gephi – Part 1中遇到了同样的问题。

  只要请求dict()对象(使用格式a = adict [key])并且密钥不在字典中,Python就会引发KeyError。 KeyError - Python Wiki

在搜索了一些内容并添加了一些打印语句之后,我意识到我的OAuth会话已过期,因此我linkedin-2-query.py脚本中的OAuth令牌的有效期更长。

由于OAuth令牌无效,因此LinkedIn API不会像脚本所期望的那样返回键"values"的字典。相反,API返回字符串'N'。 Python尝试在字符串"values"中找到字典键'N',失败,并生成KeyError: 'values'

这是一个新的,有效的OAuth令牌&amp; secret应该让API返回包含连接数据的dict。


我再次运行linkedin-1-oauth.py脚本,然后访问LinkedIn Application details page以查找我的新OAuth令牌。 (屏幕截图省略了我的应用程序的值。您应该看到每个Key,Token和&amp; Secret的字母数字值。)

enter image description here

<强> ...

enter image description here

然后,我使用新的 OAuth用户令牌 OAuth用户密钥

更新我的linkedin-2-query.py脚本
OAUTH_TOKEN = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # your updated OAuth User Token
OAUTH_TOKEN_SECRET = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # your updated OAuth User Secret

更新OAuth令牌&amp;秘密,我立即运行我的linkedin-2-query.py脚本。万岁,它运行没有错误,并从API检索我的连接数据。