从 Google 人物 API 搜索中获取姓名和 phone 号码

Obtaining both the name and phone number from a Google People API search

我正在使用 Python 中的 Google 人 API 来查询我的 Google 联系人列表。我可以使用此功能,但一个特定的操作不起作用。

results = service.people().connections().list(
    resourceName='people/me',
    pageSize=1,
    personFields='names,phoneNumbers').execute()
connections = results.get('connections', [])

for person in connections:
    data = person.get('names', [])

这行得通 -- 它给了我一个名字列表。但是,我想要一份姓名列表和 phone 号码。如果我这样做:

for person in connections:
    data = person.get('phoneNumbers', [])

这也行。我得到了 phone 个数字的列表。但是,如果我尝试同时获得两者,我将得不到任何结果:

for person in connections:
    data = person.get('names,phoneNumbers', [])

根据我对 People API 文档 (https://developers.google.com/people/api/rest/v1/people/get) 的解释,这应该可行。相反,我什么也得不到。

我做错了什么?

当您调用 person.get() 时,您 不是 调用 v1/people/get 端点,您只是从 字典中获取一个值.

之前对 service.people().connections()....execute() 的调用已经从 API 中获取了所有信息并将其放入字典列表中。

然后,当您遍历 connections 时,您会得到一个名为 person 的字典,其中包含两个键 namesphoneNumbers。 您的代码正在尝试获取名称为 names,phoneNumbers 的密钥,该密钥不存在。

不确定您如何使用 data 或您希望它是什么类型,但要让 data 同时包含姓名和电话,只需执行以下操作:

data = person

或者直接在其余代码中使用 person

正如@marmor 所说,错误在于您访问响应内容的方式。 dict.get() 方法确实同时拒绝了两个键。 您可以使用以下两种不同的方法。

# Calling them separately
personName = person.get('names', [])
personPhone = person.get('phoneNumbers',[])
# Calling them together using list compression
keys = ["names","phoneNumbers"]
data = [person.get(key) for key in keys]

你应该参考people().connections().list() to better understand the response format. In this case, it is a resource of type Person

另一种可能的近似方法是,获取姓名列表及其 phone 编号并将它们存储在字典中:

代码示例
def getNameAndPhones():
  service = people_service()
  results = service.people().connections().list(
    resourceName= "people/me",                                
    personFields='names,phoneNumbers').execute()              
  person_dict = {}           
  for per in  results['connections']:                         
    try:
      name =  per['names'][0]['displayName'] 
      # As the response is an array
      # we need to do some list comprehension
      phoneNumbers = [x['value'] for x in per['phoneNumbers']]         
      person_dict[name] = phoneNumber
    except : 
      name =  per['names'][0]['displayName']         
      person_dict[name] = "No phone Number"

  print(person_dict)
  return person_dict
回应
{
   "Eco":["00112233"],
   "Maxim maxim":"No phone Number",
   "dummy super":[
      "123123123",
      "12312309812390"
   ]
}
文档