自动查询Facebook页面并将结果存储在dict中

时间:2018-03-28 13:57:16

标签: python-3.x facebook-graph-api

我有一个facebook页面名称列表

pages = ['financialtimes', 'dailytelegraph', 'theguardian']

我想自动将这些名称存储在dict中;我已经有了以下功能来质疑它们,但不知道如何在字典中获得结果

app_id = "my_app_id"
app_secret = "my_app_secret"
access_token = app_id + "|" + app_secret

def FacebookIDs(page_name, access_token=access_token):
    """ get page's numeric information """  
    # construct the URL string
    base = "https://graph.facebook.com/v2.4"
    node = "/" + str(page_name)
    parameters = "/?access_token=%s" % access_token
    url = base + node + parameters
    # retrieve data    
    with urllib.request.urlopen(url) as url:
        data = json.loads(url.read().decode()) 
    print(data)

1 个答案:

答案 0 :(得分:0)

您的功能中只更改了一行代码:

import json
def FacebookIDs(page_name, access_token=access_token):
    """ get page's numeric information """  
    # construct the URL string
    base = "https://graph.facebook.com/v2.4"
    node = "/" + str(page_name)
    parameters = "/?access_token=%s" % access_token
    url = base + node + parameters
    # retrieve data    
    with urllib.request.urlopen(url) as url:
        data = json.loads(url.read().decode()) 
    return data #change only this line

如上所示更改最后一行。然后定义一个空字典并遍历列表,将键定义为列表项,将值定义为函数的结果。 (返回的JSON有两个条目,因此您需要选择条目id。)

pages_ids_dict = {}
for page in pages:
    pages_ids_dict[page] = FacebookIDs(page, access_token)['id']