Instagram API : 모든 사용자 미디어를 얻는 방법?
일반적으로 모든 사용자 미디어를 가져와야합니다.
사용자가 250 장 이상의 사진을 가지고 있습니다.
나는한다 /users/1/media/recent/?access_token=...&count=250
하지만 20 장의 사진 만 반환됩니다.
인스 타 그램에는 미디어를 얻는 데 한계가있을 수 있습니다. 그렇다면 응답에는 문제를 해결하기위한 페이지 매김이 있습니다. 하지만 최대 증명 사진 만 있습니다. 페이지를 매길 첫 번째 (분) ID 사진을 어떻게 알 수 있습니까?
맞습니다. Instagram API는 호출 당 20 개의 이미지 만 반환합니다. 따라서 페이지 매김 기능을 사용해야합니다.
API 콘솔을 사용하려는 경우. 먼저 Instagram 로그인을 통해 API 콘솔을 인증하도록 허용해야합니다. 이렇게하려면 인증 드롭 다운에서 OAUTH2를 선택해야합니다.
인증되면 왼쪽 메뉴를 사용하여 users / {user-id} / media / recent endpoint를 선택합니다. 따라서 {user-id}에 대한이 게시물을 위해 self로 대체 할 수 있습니다. 그런 다음 계정을 사용하여 정보를 검색합니다.
최소한이 엔드 포인트에 대해 GET을 수행하는 데 필요한 것입니다. 보내면 json이 반환됩니다. 모든 서버 정보 다음에 반환 된 정보의 맨 위에 next_url 및 next_max_id가있는 페이지 매김 부분이 표시됩니다.
next_max_id는 쿼리의 매개 변수로 사용할 것입니다. max_id는 처음 반환 된 20 개 중 가장 오래된 이미지의 ID입니다. 이 이미지보다 이전 이미지를 반환하는 데 사용됩니다.
원하지 않는 경우 max_id를 사용할 필요가 없습니다. 실제로 더 많은 이미지 쿼리를 시작하려는 이미지의 ID를 가져올 수 있습니다.
따라서 반환 된 데이터에서 max_id를 매개 변수 max_id에 복사합니다. 요청 URL은 https://api.instagram.com/v1/users/self/media/recent?max_id=XXXXXXXXXXX 와 같은 형식이어야합니다. 여기서 XXXXXXXXXXX는 max_id입니다. 다시 보내기를 누르면 다음 20 장의 사진을 얻을 수 있습니다.
거기에서 업데이트 된 max_id도 받게됩니다. 그런 다음 다시 사용하여 결국 사용자의 모든 사진을 살펴볼 때까지 다음 20 장의 사진 세트를 얻을 수 있습니다.
제가 작업중인 프로젝트에서 제가 한 것은 최초의 최근 미디어 요청에서 반환 된 처음 20 장의 사진을로드하는 것입니다. 그런 다음 데이터 ID로 이미지를 할당합니다 (-id는 실제로 원하는대로 지정할 수 있음). 그런 다음 사진 세트 하단에 추가로드 버튼을 추가했습니다.
버튼을 클릭하면 jQuery를 사용하여 마지막 이미지와 데이터 ID 속성을 가져와이를 사용하여 ajax를 통해 get 호출을 생성하고 결과를 이미 페이지에있는 사진 끝에 추가합니다. 버튼 대신에 무한 스크롤 효과를 갖도록 교체 할 수 있습니다.
도움이 되었기를 바랍니다.
선택적 매개 변수 개수를 -1로 설정하여이 문제를 해결했습니다.
Instagram 개발자 콘솔 의 문제였습니다 . max_id
그리고 min_id
이 작동하지 않습니다.
에 대한 정보는 http://instagram.com/developer/endpoints/ 를 참조하십시오 pagination
. next_url
결과가 pagination
객체 에서 지정 하는 다음 부분을 요청할 때마다 결과 페이지를 순차적으로 진행해야 합니다.
내가해야 할 일은 (Javascript에서) 재귀 함수를 사용하여 모든 페이지를 통과하는 것입니다. 인스 타 그램 사용자가 수천 장의 사진을 가질 수 있기 때문에 위험합니다 (따라서 제어해야합니다).이 코드를 사용합니다. (내 생각에는 계수 매개 변수,별로하지 않습니다)
instagramLoadDashboard = function(hash)
{
code = hash.split('=')[1];
$('#instagram-pictures .images-list .container').html('').addClass('loading');
ts = Math.round((new Date()).getTime() / 1000);
url = 'https://api.instagram.com/v1/users/self/media/recent?count=200&min_timestamp=0&max_timestamp='+ts+'&access_token='+code;
instagramLoadMediaPage(url, function(){
galleryHTML = instagramLoadGallery(instagramData);
//console.log(galleryHTML);
$('#instagram-pictures .images-list .container').html(galleryHTML).removeClass('loading');
initImages('#instagram-pictures');
IGStatus = 'loaded';
});
};
instagramLoadMediaPage = function (url, callback)
{
$.ajax({
url : url,
dataType : 'jsonp',
cache : false,
success: function(response){
console.log(response);
if(response.code == '400')
{
alert(response.error_message);
return false;
}
if(response.pagination.next_url !== undefined) {
instagramData = instagramData.concat(response.data);
return instagramLoadMediaPage(response.pagination.next_url,callback);
}
instagramData = instagramData.concat(response.data);
callback.apply();
}
});
};
instagramLoadGallery = function(images)
{
galleryHTML ='<ul>';
for(var i=0;i<images.length;i++)
{
galleryHTML += '<li><img src="'+images[i].images.thumbnail.url+'" width="120" id="instagram-'+images[i].id+' data-type="instagram" data-source="'+images[i].images.standard_resolution.url+'" class="image"/></li>';
}
galleryHTML +='</ul>';
return galleryHTML;
};
사진 갤러리 인쇄와 관련된 몇 가지 항목이 있습니다.
사용자의 모든 게시물을 가져 오기 위해 최상의 재귀 기능을 사용하십시오.
<?php
set_time_limit(0);
function getPost($url,$i)
{
static $posts=array();
$json=file_get_contents($url);
$data = json_decode($json);
$ins_links=array();
$page=$data->pagination;
$pagearray=json_decode(json_encode($page),true);
$pagecount=count($pagearray);
foreach( $data->data as $user_data )
{
$posts[$i++]=$user_data->link;
}
if($pagecount>0)
return getPost($page->next_url,$i);
else
return $posts;
}
$posts=getPost("https://api.instagram.com/v1/users/CLIENT-ACCOUNT-NUMBER/media/recent?client_id=CLIENT-ID&count=33",0);
print_r($posts);
?>
Instagram PHP API의 사용자 페이지 매김 : https://github.com/cosenary/Instagram-PHP-API/wiki/Using-Pagination
그런 것 :
$Instagram = new MetzWeb\Instagram\Instagram(array(
"apiKey" => IG_APP_KEY,
"apiSecret" => IG_APP_SECRET,
"apiCallback" => IG_APP_CALLBACK
));
$Instagram->setSignedHeader(true);
$pictures = $Instagram->getUserMedia(123);
do {
foreach ($pictures->data as $picture_data):
echo '<img src="'.$picture_data->images->low_resolution->url.'">';
endforeach;
} while ($pictures = $instagram->pagination($pictures));
In June 2016 Instagram made most of the functionality of their API available only to applications that have passed a review process. They still however provide JSON data through the web interface, and you can add the parameter __a=1
to a URL to only include the JSON data.
max=
while :;do
c=$(curl -s "https://www.instagram.com/username/?__a=1&max_id=$max")
jq -r '.user.media.nodes[]?|.display_src'<<<"$c"
max=$(jq -r .user.media.page_info.end_cursor<<<"$c")
jq -e .user.media.page_info.has_next_page<<<"$c">/dev/null||break
done
Edit: As mentioned in the comment by alnorth29, the max_id
parameter is now ignored. Instagram also changed the format of the response, and you need to perform additional requests to get the full-size URLs of images in the new-style posts with multiple images per post. You can now do something like this to list the full-size URLs of images on the first page of results:
c=$(curl -s "https://www.instagram.com/username/?__a=1")
jq -r '.graphql.user.edge_owner_to_timeline_media.edges[]?|.node|select(.__typename!="GraphSidecar").display_url'<<<"$c"
jq -r '.graphql.user.edge_owner_to_timeline_media.edges[]?|.node|select(.__typename=="GraphSidecar")|.shortcode'<<<"$c"|while read l;do
curl -s "https://www.instagram.com/p/$l?__a=1"|jq -r '.graphql.shortcode_media|.edge_sidecar_to_children.edges[]?.node|.display_url'
done
To make a list of the shortcodes of each post made by the user whose profile is opened in the frontmost tab in Safari, I use a script like this:
sjs(){ osascript -e'{on run{a}','tell app"safari"to do javascript a in document 1',end} -- "$1";}
while :;do
sjs 'o="";a=document.querySelectorAll(".v1Nh3 a");for(i=0;e=a[i];i++){o+=e.href+"\n"};o'>>/tmp/a
sjs 'window.scrollBy(0,window.innerHeight)'
sleep 1
done
Use the next_url
object to get the next 20 images.
In the JSON response there is an pagination
array:
"pagination":{
"next_max_tag_id":"1411892342253728",
"deprecation_warning":"next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id":"1411892342253728",
"next_min_id":"1414849145899763",
"min_tag_id":"1414849145899763",
"next_url":"https:\/\/api.instagram.com\/v1\/tags\/lemonbarclub\/media\/recent?client_id=xxxxxxxxxxxxxxxxxx\u0026max_tag_id=1411892342253728"
}
This is the information on specific API call and the object next_url
shows the URL to get the next 20 pictures so just take that URL and call it for the next 20 pictures.
For more information about the Instagram API check out this blogpost: Getting Friendly With Instagram’s API
Instagram developer console has provided the solution for it. https://www.instagram.com/developer/endpoints/
To use this in PHP, here is the code snippet,
/**
**
** Add this code snippet after your first curl call
** assume the response of the first call is stored in $userdata
** $access_token have your access token
*/
$maximumNumberOfPost = 33; // it can be 20, depends on your instagram application
$no_of_images = 50 // Enter the number of images you want
if ($no_of_images > $maximumNumberOfPost) {
$ImageArray = [];
$next_url = $userdata->pagination->next_url;
while ($no_of_images > $maximumNumberOfPost) {
$originalNumbersOfImage = $no_of_images;
$no_of_images = $no_of_images - $maximumNumberOfPost;
$next_url = str_replace("count=" . $originalNumbersOfImage, "count=" . $no_of_images, $next_url);
$chRepeat = curl_init();
curl_setopt_array($chRepeat, [
CURLOPT_URL => $next_url,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $access_token"
],
CURLOPT_RETURNTRANSFER => true
]);
$userRepeatdata = curl_exec($chRepeat);
curl_close($chRepeat);
if ($userRepeatdata) {
$userRepeatdata = json_decode($userRepeatdata);
$next_url = $userRepeatdata->pagination->next_url;
if (isset($userRepeatdata->data) && $userRepeatdata->data) {
$ImageArray = $userRepeatdata->data;
}
}
}
}
참고URL : https://stackoverflow.com/questions/10881511/instagram-api-how-to-get-all-user-media
'developer tip' 카테고리의 다른 글
bash 쉘 명령 행에 대한 매개 변수 -e의 의미는 무엇입니까? (0) | 2020.11.18 |
---|---|
R % in % 연산자 (0) | 2020.11.18 |
내가 만든 .clj Clojure 파일을 어떻게 실행할 수 있습니까? (0) | 2020.11.17 |
ASP.NET MVC에서 Tempdata 사용-모범 사례 (0) | 2020.11.17 |
노드의 PassportJS가 로그 아웃시 세션을 제거하지 않는 이유 (0) | 2020.11.17 |