Gabotronix
1 month ago
137
0
General

Keep facebook login session with PHP puphpeteer?

Posted 1 month ago by Gabotronix

Hi everybody, I'm using puphpeteer which is a PHP bridge for node's puppeteer supporting the whole API, I will be scraping different facebook pages looking for some info, for this I have to login with my credentials and then go to targeted facebook page.

My objective is to ONLY LOG INONE TIME and than once logged, use facebook session/log in cookies to keep my session for subsequent urls, afaik this would be possible to do but I haven't found any examples on how to do this with PHP Puphpeteer.

Here is my code:

use Nesk\Puphpeteer\Puppeteer;
use Nesk\Rialto\Data\JsFunction;
use Nesk\Puphpeteer\Resources\ElementHandle;


public function scrapeFacebookForBirthdays()
    {
        $cookies = null;

        $puppeteer = new Puppeteer();
        $browser = $puppeteer->launch([ 'headless' => false, 'slowMo' => 250 ]);
        $browser->setUserAgent('Opera/9.80 (Windows NT 6.2; WOW64) Presto/2.12.388 Version/12.17');

        $page = $browser->newPage();

        
        //Check if cookies are set or not, if not set it means we have to log in ONCE, but HOW to cjeck for cookies, where to save them?
        if (!$cookies)
        {
            $page->goto("https://www.facebook.com/login", [ 'waitUntil' => "networkidle2" ]);
            $page->type("#email", $username, [ 'delay' => 30 ]);
            $page->type("#pass", $password, [ 'delay' => 30 ]);
            $page->click("#loginbutton");

            sleep(5);

            $page->waitForNavigation([ 'waitUntil' => "networkidle0" ]);

            try 
            {
                echo "success login";
                $page->waitFor('[data-click="profile_icon"]');
            }
            catch (Exception $e)
            {
                echo "failed to login";
                $browser->close();
            }

            //Where to save cookies for next url scrape??
            $cookies = $page->cookies();
        }
        else
        {
            //User Already Logged In
            $page->setCookie($cookies);
        }
    }

Thanks in advance!

Please sign in or create an account to participate in this conversation.