<jupyter_start><jupyter_text>練習- 取得 FB 粉絲團中所有文章的按讚與分享數- 使用 [Graph API](https://developers.facebook.com/tools/explorer/)- https://www.facebook.com/DoctorKoWJ- 輸出成 CSV<jupyter_code>import os
import requests
import pandas as pd

from datetime import datetime
# 透過 Graph API 觀察文章 ID 與 token
fanpage_id = '136845026417486'
token = ''
url = 'https://graph.facebook.com/v2.11/{}/posts?fields={}&access_token={}'.format(
    fanpage_id, 'id,created_time,name,likes.limit(0).summary(true),shares,message', token
)

posts = []
pages = 0

while True:
    resp = requests.get(url)
    data = resp.json()
    posts += data['data']
    pages += 1
    
    if 'next' not in data['paging']:
        print('EOF')
        break
        
    else:
        url = data['paging']['next']
        print('page {}'.format(pages))
posts_summary = []
for post in posts:
    p = {}
    for k, v in post.items():
        if k == 'likes' and 'summary' in v and 'total_count' in v['summary']:
            p['total_likes'] = v['summary']['total_count']
        elif k == 'shares' and 'count' in v:
            p['total_shares'] = v['count']
        else:
            p[k] = v
    posts_summary.append(p)

df = pd.DataFrame.from_records(posts_summary)
df.head()
results = os.path.abspath('../results')
if not os.path.exists(results):
    os.makedirs(results)
    
filename = os.path.join(results, 'fanpage_{}.csv'.format(fanpage_id))
df.to_csv(filename, index=False)
print('Save file - {}'.format(filename))<jupyter_output>Save file - /home/dirl/github/Python-Crawling-Tutorial/results/fanpage_136845026417486.csv
{'fraction_non_alphanumeric': 0.16075949367088607, 'fraction_numerical': 0.02278481012658228, 'mean_word_length': 3.3434065934065935, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 3, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '475060', 'license': 'Apache-2.0', 'n_tokens_mistral': 617, 'n_tokens_neox': 594, 'n_words': 117, 'path': '03_graph_api/01_facebook_crawling_fanpage_likes_shares.ipynb', 'repo_name': 'afunTW/Python-Crawling-Tutorial', 'size': '1580'}