• info@dcc-dp.id
  • Alamat: Jl. Perintis Kemerdekaan III, BTN Antara Blok A11/02 Tamalanrea, Makassar, Indonesia

python:facebook albums photos download dan dump

Admins 5 Comments Desember 23, 2011

python:facebook albums photos download dan dump

Pendahuluan
Halo teman-teman back lagi bersama si penulis jimmyromanticdevil aka rahmat ramadhan iryanto .kali ini saya akan share code saya yang baru saya buat yaitu fb_dowpic.py (facebook download all picture) yah jadi code ini berfungsi untuk mendownload semua album-album di profil facebook seseorang . code ini berawal dari si penulis yang ingin mendownload / mengambil semua foto-foto pacar penulis :P axixixiixix ...ya yang dimana kita tau bahwa kl secara manual untuk mendownload / mengambil semua album foto di facebook akan sangat - sangat ribet dan memakan otot : buka profil facebook -> klick photo -> pilih dan klick album -> klick photos - > klick kanan n "save image as" -> lanjut klick next - > klick kanan n "save image as" dan selanjutnya setelah habis klick lagi albums lain klick photos - > klick kanan n "save image as" -> lanjut klick next - > klick kanan n "save image as" dan selanjutnya sampai album selesai di klick dan photo di save .WAWAWAW .. bayangkan seberapa capeknya kita lakukan itu belum lagi kl koneksi lelet bisa2 modem kalian lempar sampai patah pengalaman penulis kemarin LOL.

 

Proof Of Concept
Ada baiknya saya fotokan dulu Flowcartnya.Lihat di sini : http://pastebin.com/kec1hR2T atau bisa melihat di bawah ini
[code]
      __________
     /                       \
     |  start              |
     \__________/
          |
          |
     _____v___________   
    / Read email &   /
   / password       /
  /  and login     /
 /________________/
          |
          |
  ________v_______
 |  Get Acces     |
 |  Token Key     |
 |________________|       
          |
          |
  ________v_______
 |  Get albums url|
 |  and list      |
 |  of album      |
 |________________|       
          |
          |
  ________v_______
 | Get the id of       |
 | The albums that  |
 | matches the       |
 | albums url           |
 |________________|
          |
          |
  ________v_______
 | Get the list   |
 | of photos      |
 | in that albums |
 |________________|       
          |
          |
  ________v_______
 | Get the source |
 | photo url of   |
 | each photo in  |
 | the list       |
 |________________|  
          |
          |
  ________v_______
 | download and   |
 | save photos    |
 |________________|             
          |
          |
      ____v_____
     /          \
     |  stop    |
     \__________/
[/code]
Jadi Proof Of Concept dari program ini adalah pertama - tama saya akan membaca email dan password
dan memprosesnya yang dimana akan di gunakan untuk login ke url facebook . yang pada saat proses pertama - tama kita setup dlu
urllib dan lib untuk menghandle cookies kita nanti . teknik ini sangat tricky dalam pengambilan sebuah cookies cukup dengan mengunakan
     [code]
     CHandler = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
     opener = urllib2.build_opener(CHandler)
     opener.addheaders = [('User-agent', random.choice(user_agent))]
     urllib2.install_opener(opener)
     print 'Loading..Please Wait....!!'
     url_fb = opener.open('http://facebook.com/index.php')
     [/code]

nah lihat di atas sy mengunakan random.choice(user_agent)) jadi saya lagi-lagi mengunakan random chooise user agent di karenakan takutnya kita kena filter lagi dari facebook . nah jadi selanjutnya untuk membuka url itu kita hanya cukup mengunakan opener.open('http://facebook.com/index.php') == opener.open(url) yang dimana cookies sudah di set di var opener.selanjutnya saya akan melakukan scraping terhadap page facebook . yang dimana saya akan mencari post_form id untuk mempost data pada saat login ini perlu tanpa ini kita tidk bisa melakukan ap2 .. saya mengunakan sedikit teknik REGEX(REGULAR EXPRESS ) untuk melakukan matching terdapat isi dari post_form_id ini


code html pada facebook page :
    [code]< input type = "hidden" autocomplete = "off" name = "post_form_id" value = "8466c6978e380b70c90ead7fe65f95cf" / >[/code]
    [code]re.search('name="post_form_id" value="(\w+)"', url_fb.read())[/code] --> kita ingin mendapatkan ini :   
    "8466c6978e380b70c90ead7fe65f95cf"
    
     selanjtnya kita set values2/isi data yang akan kita post yang dimana terdapat lsd,post_form_id,charset_test,email,pass,login
     kita cek dulu apa isi html page facebook : http://pastebin.com/sacESamm atau bisa di liat di bawah
     [code]

     [/code]    
    [code]
    chatset_key = urllib.unquote_plus('%E2%82%AC%2C%C2%B4%2C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84')
    value = { 'lsd' : '',
        'post_form_id' : pattern_id.group(1),
        'charset_test' : chatset_key,
        'email' : fb_user,
        'pass' : fb_password,
        'login' : 'Login'
    }
    post_data = urllib.urlencode(value)
    print 'Logging Facebook :' + fb_user
    url_fb =  url_fb = opener.open('https://www.facebook.com/login.php?m=m&refsrc=http%3A%2F%2Fm.facebook.com%2Findex.php&refid=8',post_data)
    [/code]
    
    jadi selanjutnya lagi saya akan mencek apakah saya berhasil masuk ??? bagaimana caranya ? ya dengan sedikit teknik REGEX(REGULAR EXPRESS) lagi .
    [code]
   
    [/code]
    [code]
    if not re.search('Keluar', url_fb.read()):
           print 'Login Failed'
           exit(2)
    url_fb.close()     
    [/code]
    Di sini saya mengunakan facebook bahasa indonesia Nah yang dimana kita tau bahwa kalau kita berhasil login facebook akan ada button  keluar di menu bar kalian :P just simple logic .... jadi kalian yang mengunakan facebook bahasa inggris di sesuaikan contoh "Keluar" di ganti "Logout".
    
    Jadi kita sudah berhasil login terus apa yang akan kita lakukan sekarang ?? ya kita harus mengambil Token key kita yang di berikan dari facebook .
    [code]

[/code]
    [code]
    url_fb = opener.open('http://developers.facebook.com/docs/reference/api')
    data_api = url_fb.read()
    pattern_token = re.search('access_token=(.*?)"', data_api)
    token_key = pattern_token.group(1)
    print 'Token Key : %s' % token_key
    [/code]
    Nah kita lihat bahwa pertama tama kita buka dulu url = http://developers.facebook.com/docs/reference/api yang dimana di halaman page itu terdapat acces token key kita. dan sedikit lagi mengunakan teknik REGEX(REGULAR EXPRESS)

untuk match data yang di cari pada kali ini v
access_token=AAAAAAITEghMBACOsJUpa7hWYCHSXJQw0MP3WQNAmPSJqjj

CSg3UeM3osj4Vc57u8KZBtyhYJE54ncxt9tZB0DsoAw5dilRFjGEqUzZBGIZBmnKUseANu .
 
    Trus apa yang kita akan lakukan setelah mendapatkan ini ?? ya tentu kita akan membuka profil pacar saya :P
nah perlu di ingat di sini kita tidak akan lagi menscrap html tag2 pada page facebook tapi sturc API key Facebook yang dimana berbentuk format JSON . contoh :
    [code]
    {
   "data": [
      {
         "id": "276898572331301",
         "from": {
            "name": "Yunita Andyta Pearl",
            "id": "100000334815949"
         },
         "name": "Pamer dulu",
         "link": "http://www.facebook.com/album.php?fbid=276898572331301&id=100000334815949&aid=69062",
         "cover_photo": "276900655664426",
         "count": 6,
         "type": "normal",
         "created_time": "2011-10-08T16:25:43+0000",
         "updated_time": "2011-10-25T05:05:53+0000",
         "can_upload": false,
     .......
     ......    
    [/code]
    [code]
    # Dapatkan Album List
    url_fb = opener.open('https://graph.facebook.com/%s/albums?access_token=%s' % (profil_id,token_key))
    furl_fb = url_fb.read()
    data = json.loads(furl_fb)
    for x in data['data']:
        fid = x['id']
        link = x["link"]
        fname = x['name']
        fcount = int(x['count'])
        print '\nName Albums : ',fname
        print 'How Many Photos In Albums : ',fcount
        print 'Link Album Photos : ',link
    [/code]
    Sebelum ini alangkah baiknya kalian membaca2 seputar json ini di : http://www.json.org/ & http://docs.python.org/library/json.html
    nah coba liat pada code di atas di sini mendump semua isi data di halaman facebook yang berformat json dan mendump datanya yang akan di format lagi sebagai json code data = json.loads(furl_fb) nah pada saat selesai kita load dengan looping seluruh isi datanya yang dimana saya hanya akan mengambil id,link,name
    [code]
     "id": "276898572331301",
     "link": "http://www.facebook.com/album.php?fbid=276898572331301&id=100000334815949&aid=69062", "name": "Pamer dulu",
    [/code]
    
    dengan cara
    [code]
    for x in data['data']:
        fid = x['id']
        link = x["link"]
        fname = x['name']
        fcount = int(x['count'])
    [/code]
    dan selanjutnya saya print / tampilkan datanya ..yang dimana name albums,how many photos in album dan link album . ;)
    
    so next terakhir ..  saya lagi lagi akan mengandalkan json untuk menghandle page facebook yang berformat json . dan kali ini kita akan
    membuka page album dan id albums dan akhirnya mendownload photonya ..
    [code]
    {
   "data": [
      {
         "id": "104084936279333",
         "from": {
            "name": "Yunita Andyta Pearl",
            "id": "100000334815949"
         },
         "tags": {
            "data": [
               {
                  "id": "1369081925",
                  "name": "Issaniar Syarief",
                  "x": 64.8515,
                  "y": 62.8571,
                  "created_time": "2010-01-23T07:49:49+0000"
               },
               .......
               .......
         "picture": "http://photos-f.ak.fbcdn.net/hphotos-ak-snc3/18980_104084936279333_100000334815949_101102_3079223_s.jpg",
         "source": "http://a6.sphotos.ak.fbcdn.net/hphotos-ak-snc3/18980_104084936279333_100000334815949_101102_3079223_n.jpg",
    [/code]
    [code]
        url_fb1 = opener.open('https://graph.facebook.com/%s/photos?access_token=%s&limit=500'%(fid,token_key))
        data_fb = url_fb1.read()
        data1 = json.loads(data_fb)
        for i in data1['data']:
            src = i["source"]
            id_picture = i["id"]
            print src
            url = opener.open(src)
            img_name = '%s'%str(id_picture)
            output = open(img_name,'wb')
            output.write(url.read())output.close()        
    [/code]   
        nah kita lihat perintah hampir sama seperti sebelumnya cuman di sini saya hanya akan mengambil source dan id saja yang nanti source di gunakan sebagai url untuk mendownload photo facebooknya dan id untuk nama file yang tersave
        perintah ini di gunakan untuk mensave/mendownload photos di facebook
    [code]
            url = opener.open(src)
            img_name = '%s'%str(id_picture)
            output = open(img_name,'wb')
            output.write(url.read())
     [/code]
     Just simple code on Python :P..
     
     dan di sini saya mengunakan sebuah thread untuk mempercepat sebuah proses jadi program di atas tidak berjalan dengan single-thread tapi multithread .. ;)
     [code]
     if __name__ == '__main__':
   try:  
     t = Thread(target=main)
     t.start()
     [/code]
     
     ---[ Code lengkap
[code]
#!/usr/bin/python
# Coder : jimmyromanticdevil aka rahmat ramadhan iryanto
# Fb_downpic.py is tools for download all photos albums from facebook
# Dedicate for my Princess and lovely yunita andyta perl <3 Love u Honey ...
#
# Inspirated :
#   I was made this tools for Download all my girlfriend Photos on facebook
#   
# Proc of Consep :
#      The first things i just login to facebook using username n password and url login facebook . after that i
#   am going to url http://developers.facebook.com/docs/reference/api to scrap n get my acces token key and using little
#   regex consep for find and match my token key. after i got
#   my acces token i am going to https://graph.facebook.com/%s/albums?access_token=%s' % (profil_id,token_key)
#   profil_id = is my girl profil id and token_key so i scrap the link albums url then i dumps in json format and after
#   that i am scrap the url source of image from albums and download the image from the url source. just simple logic . ;)
#
# Little refrensi :
#     I suggest you reading my articel/tutorial basic of this code on
#     http://jimmyromanticdevil.wordpress.com/2011/11/27/python-web-crawlerromanticdevil-crawler-py/
#     http://jimmyromanticdevil.wordpress.com/2011/11/26/python-web-scraping-parsingscreen-scraping-web-pages/
#   
# Special thanks to :
#     My Princess and lovely Yunita Andyta Perl without you maybe this code will never exist .. :P

#
'''
Copyright (c) 2011, Jimmyromanticdevil
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import sys
import re
import urllib
import urllib2
import cookielib
import json
import threading
from threading import Thread
import random
user_agent = ['Mozilla/4.0 (compatible; MSIE 5.0; SunOS 5.10 sun4u; X11)',
        'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.2pre) Gecko/20100207 Ubuntu/9.04 (jaunty) Namoroka/3.6.2pre',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant opener;',
        'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)',
            'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)',
            'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6)',
            'Microsoft Internet Explorer/4.0b1 (Windows 95)',
            'Opera/8.00 (Windows NT 5.1; U; en)',
        'amaya/9.51 libwww/5.4.0',
        'Mozilla/4.0 (compatible; MSIE 5.0; AOL 4.0; Windows 95; c_athome)',
        'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
        'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; ZoomSpider.net bot; .NET CLR 1.1.4322)',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; QihooBot 1.0 qihoobot@qihoo.net)',
        'Mozilla/4.0 (compatible; MSIE 5.0; Windows ME) Opera 5.11 [en]'
]


def main():
    fb_user = '' #--> your user facebook
    fb_password = ''#--> your facebook password
    profil_id = '' #--> Your target profil id    
    CHandler = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
    opener = urllib2.build_opener(CHandler)
    opener.addheaders = [('User-agent', random.choice(user_agent))]
    urllib2.install_opener(opener)
    print 'Loading..Please Wait....!!'
    url_fb = opener.open('http://facebook.com/index.php')
    pattern_id = re.search('name="post_form_id" value="(\w+)"', url_fb.read())
    url_fb.close()
    chatset_key = urllib.unquote_plus('%E2%82%AC%2C%C2%B4%2C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84')
    value = { 'lsd' : '',
        'post_form_id' : pattern_id.group(1),
        'charset_test' : chatset_key,
        'email' : fb_user,
        'pass' : fb_password,
        'login' : 'Login'
    }
    post_data = urllib.urlencode(value)
    print 'Logging Facebook :' + fb_user
    url_fb = opener.open('https://www.facebook.com/login.php?m=m&refsrc=http%3A%2F%2Fm.facebook.com%2Findex.php&refid=8',post_data)
    if not re.search('Keluar', url_fb.read()):
           print 'Login Failed'
           exit(2)
    url_fb.close()       

    # Dapatkan Acces Token
    url_fb = opener.open('http://developers.facebook.com/docs/reference/api')
    data_api = url_fb.read()
    pattern_token = re.search('access_token=(.*?)"', data_api)
    token_key = pattern_token.group(1)
    print 'Token Key : %s' % token_key

    # Dapatkan Album List
    print 'Get Album List & Download the photos'
    url_fb = opener.open('https://graph.facebook.com/%s/albums?access_token=%s' % (profil_id,token_key))
    furl_fb = url_fb.read()
    data = json.loads(furl_fb)
    for x in data['data']:
        fid = x['id']
        link = x["link"]
        fname = x['name']
        fcount = int(x['count'])
        print '\nName Albums : ',fname
        print 'How Many Photos In Albums : ',fcount
        print 'Link Album Photos : ',link
        
        url_fb1 = opener.open('https://graph.facebook.com/%s/photos?access_token=%s&limit=500'%(fid,token_key))
        data_fb = url_fb1.read()
        data1 = json.loads(data_fb)
        for i in data1['data']:
            src = i["source"]
            id_picture = i["id"]
            print src
            url = opener.open(src)
            img_name = '%s'%str(id_picture)
            output = open(img_name,'wb')
            output.write(url.read())
        output.close()        
     
if __name__ == '__main__':
   try:  
     t = Thread(target=main)
     t.start()
   except Exception,err:
     t.stop()  
[/code]     Source lebih lengkapnya download di sini : http://pastebin.com/vZedfvuX
 
  Output Example :
  http://i39.tinypic.com/2iks2s.jpg

  http://i42.tinypic.com/1zd5izo.jpg 


  ---[ kesimpulan
Lihat seberapa simplenya .. dengan hanya sedikit line code python saya sudah bisa mendump semua isi file page html dan mendownload file2 image yang terdapat pada website yaitu facebook pada code kali ini dengan hanya beberapa teknik yang saya gunakan yaitu web scrapping/Parse html,Regular express,Json Dumps/Json Scrap/Json Parse,Cookies handling dan terkahir Threading .. ya jadi untuk berinteraksi dengan sebuah website di internet beberapa teknik ini sangat di butuhkan untuk membuat sebuah code yang sudah berinteraksi dengan sebuah website .
 
so selanjutnya saya serahkan kepada kalian kl tidak mengerti silahkan di tanya bisa tinggalkan comment dan juga silahkan di edit dan dikembangkan source codenya sesuka kalian tapi jangan lupa untuk mencantumkan author aslinya :P ..ok happy coding n happy researching kurang lebihnya mohon maaf .. ;)

Special Thanks to People
My Princess Yunita Andyta Perl without you this code will never exist,5ynl0rd(my greats master),RR12,ardhe defaurteens,ahmad asto,and all my friend and YOU ^.^ Without you all i am nothing ..
Special thanks community & organiz
Python Indonesia(http://python.or.id) , Makassarhacker(http://makassarhacker.com/) , Dipanegara computer club (http://www.dcc-dp.org/)


Real Source : http://jimmyromanticdevil.wordpress.com/2011/12/23/pythonfacebook-albums-photos-downloaddump/ 

 

  • Share: