本篇文章更新時間:2020/04/27
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣 或 新台幣 贊助支持。
有鑒於 Instagram 發了個公告,表示 2020/06/29 後就要取消所有舊版本 API 存取,都移轉至 Facebook Graph API 的方式整合進 Facebook 中。
Instagram 其實 2019 年就已先公告過,所以近期很多 WordPress 裡原本使用好好的方法都開始失靈,不過就是那個 BUT!有一款主題 jNews
的卻沒事,還能照常使用,心想有空來拆解看看他的秘密。
結果經拆解後才發現,原來它純粹套用「使用者帳號」的部分是用最暴力的爬蟲方式! 這也行XD
把 code 整理一下後放出來:
function mxp_get_instagram_photos($username) {
if ($username == "") {
return array();
}
$url = "https://www.instagram.com/" . $username;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$output = curl_exec($ch);
curl_close($ch);
$data_images = array();
$data = explode('window._sharedData = ', $output);
$data_json = explode(';', $data[1]);
$data_json = json_decode($data_json[0], TRUE);
if (!empty($data_json['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'])) {
foreach ($data_json['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'] as $image) {
$data_images[] = array(
'id' => $image['node']['id'],
'time' => $image['node']['taken_at_timestamp'],
'like' => $image['node']['edge_liked_by']['count'],
'comment' => $image['node']['edge_media_to_comment']['count'],
'caption' => !empty($image['node']['edge_media_to_caption']['edges'][0]['node']['text']) ? $image['node']['edge_media_to_caption']['edges'][0]['node']['text'] : '',
'link' => rtrim('//instagram.com/p/' . $image['node']['shortcode'], '/\\') . '/',
'images' => array(
'display' => $image['node']['display_url'],
'thumbnail' => $image['node']['thumbnail_src'],
),
);
}
}
return $data_images;
}
後記
由於不一定是用在 WordPress 裡,所以寫法就是都改成 PHP 的方法,沒有包過 WordPress 內建的方法,且修正了他對中文的支援度。
要使用這種做法可以,不過僅能算是「應急」了!長久來說 Instagram 的 Web 版也有更新的那天,如果之後拿掉了這些參數,撈不到也不意外囉~
所以這種文很吃時效性,至少截至本篇目前發文時間來看還可以正常使用。之後有人使用失效的話歡迎留言通告XD
正確撈取資料的方法詳見:Instagram 圖形 API