Python 包装程序和命令行实用程序,用于在 Facebook Graph API 中与 Insights 数据进行交互。
Python 包装程序和命令行实用程序,用于在 Facebook Graph API 中与 Insights 数据进行交互。
facebook-insights is a command-line utility that makes it easier to interact with Insights metrics in the Facebook Graph API. Python users can also directly access the API wrapper that the CLI is built on.
Development status: the Python interface to facebook-insights is close to stable, but some things might change and others still need polish. The command-line interface is still very much a work in progress and you probably shouldn't try to use it yet.
import os
import facebookinsights as fi
# prompt for credentials on the command-line,
# get access to one or more pages
pages = fi.authenticate()
# alternatively, pass an existing page token
page = fi.authenticate(token=os.environ['FACEBOOK_PAGE_TOKEN'])Scroll down to find out more about authentication.
Facebook provides Insights data for the page as a whole (follower counts, impressions across all stories etc.), for all page posts taken together (likes for all page posts published last week etc.) and for individual posts (video plays for one particular post etc.)
# return a range of page posts
latest = page.posts.latest(10).get()
today = page.posts.range(days=1).get()
quarter = page.posts.range(months=3).get()
# look for a particular post instead
page.posts.find(url='http://fusion.net/story/37894/narcotrafficking-for-dummies-check-out-these-pics-of-bizarre-drug-smuggling-fails/')For many metrics, Facebook Insights includes historical data, so you can see e.g. how your page's fans have increased or decreased over time. However, for some page metrics and most post metrics, only lifetime metrics are available, which represent the current state of things.
# for many metrics, historical data is available, with daily, weekly
# and 4-weekly rollups, accessible through `daily`, `weekly` and
# `monthly` methods
page.insights.daily(['page_impressions', 'page_fan_adds']).range(months=1).get()
# for other metrics, there's only a lifetime total
post.insights.lifetime('post_stories').get()
# for some, it's the other way around: no total, only the daily numbers
for country_data in page.insights.daily('page_places_checkins_by_country'):
print country_dataAlso note that some metrics are updated roughly every 15 minutes whereas others can lag behind up to a day. Metrics postfixed with an asterisk in the Facebook Graph API documentation indicate frequently updated metrics.
Note: currently, facebook-insights will not throw an error if you ask for a metric at an impossible granularity. Instead, Facebook will return data at the granularity (often lifetime) that it can provide.
It is possible to ask for one or more metrics in particular.
# results will be returned as a single scalar value
page.insights.lifetime('page_impressions').get()
# results will be returned as an array
page.insights.lifetime(['page_impressions', 'page_fan_adds']).get()
# default metrics subset
page.insights.lifetime().get()If no metrics are specified, the Facebook Graph API will return a useful subset by default.
# metrics are classless, rows are named tuples
# column plucking is possible
post.lifetime()[0].page_fans
post.daily()['page_fans'][0]
post.daily('page_fans')[0]facebook-insights is built on the FacePy library, and you may pass certain low-level options to FacePy when executing queries:
post.daily('page_fans_online_per_day', retry=3)Most of this terminology applies both at the page level and at the page post level. For example:
page_impressions_unique at the page levelpage_posts_impressions_unique for interactions with any page postpost_impressions_unique about one particular postYou will find more detailed explanations of much of this terminology and a list of all story and feedback types in the Facebook Graph API Insights documentation, which is excellent.
Pending better documentation, to find out more about what properties and methods are available on Page, Post, Picture objects, please take a look at facebookinsights/graph.py.
To find out more detailed information about querying, look at Selection, PageSelection and InsightsSelection in facebookinsights/graph.py.
You cannot use the Facebook Graph API with your Facebook username and password. Instead, you must authenticate through oAuth, first getting a user access token and then using that token to find the access tokens to the Facebook Pages for which you are an admin or for which you otherwise have permission to view the insights data.
Short term access (a couple of hours) is most easily gained through the Graph API Explorer.
Get Access Token near the top of the pageme/accounts endpoint by entering it and clicking submitOn the command line:
# WARNING: suggested interface, not built yet
# use a token on every request
insights posts \
--token \
--since 2014-08-01 \
--until 2014-08-10 \
--metrics post_impressions
# use a saved token from a `~/.facebookinsights`
# INI file instead
insights posts \
--profile In Python:
import facebookinsights as fi
page = fi.authenticate(token='your page token goes here')It is also possible to ask Facebook for page tokens that remain valid indefinitely unless revoked by the page owner.
Apps > Create a New App~/.bashrcNative or desktop apphttp://localhost:5000/ to the Valid OAuth redirect URIs.If you intend to make your app public at some point, there are various other steps to go through: whitelisting callback URLs, going through the Facebook app approval process and so on.
If on the other hand you just want to analyze your own Facebook Insights data, you'll probably never need to look at your app settings again.
On the command-line, get authorization and save the resulting page tokens:
# WARNING: suggested interface, not built yet
# provide client_id and client_secret
insights auth
# use a profile from a `~/.facebookinsights`
# INI file instead
insights auth --profile In Python:
import facebookinsights as fi
# this will launch a web browser to authenticate
pages = fi.authenticate(
client_id='your client id',
client_secret='your client secret',
)If no arguments to authenticate are specified, facebook-insights will look for environment variables named FACEBOOK_INSIGHTS_CLIENT_ID and FACEBOOK_INSIGHTS_CLIENT_SECRET which correspond to the App ID and App Secret you got from your app's settings page earlier.
import facebookinsights as fi
# this will launch a web browser to authenticate
pages = fi.authenticate()pages will be a list of Page objects. You can access a page's token with page.token, which means you can make save those tokens for later use. This is especially important for analyses and other code that runs unattended, as getting new tokens through an oAuth authorization process always requires user interaction.
Here's an example that uses your system's keychain to store credentials:
import keyring
import json
import facebookinsights as fi
token = keyring.get_password('facebook-insights', 'test')
if token:
page = fi.authenticate(token=token)
else:
page = fi.authenticate()[0]
keyring.set_password('facebook-insights', 'test', page.token)An example of how to integrate Facebook oAuth authorization in a Flask web app is provided in examples/server.py. The process is very similar for Django and other Python web frameworks:
暂无开放 Issues,或尚未同步最近议题。