Guzzle + Symfony DomCrawler 예제 > 메모

본문 바로가기
사이트 내 전체검색

메모

php Guzzle + Symfony DomCrawler 예제

페이지 정보

profile_image
작성자 최고관리자
댓글 0건 조회 35회 작성일 25-10-21 13:09

본문

설치


composer require guzzlehttp/guzzle symfony/dom-crawler symfony/css-selector

<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use Symfony\Component\DomCrawler\Crawler;

$client = new Client([
    'timeout' => 15,
    'headers' => ['User-Agent' => 'MyScraperBot/1.0'],
]);

$res = $client->get('https://example.com/news');
$html = (string) $res->getBody();

$crawler = new Crawler($html);

// CSS 선택자로 쉽게 가져오기
$title = $crawler->filter('h1.title')->first()->text();
echo $title . PHP_EOL;

// 기사 링크들
$crawler->filter('a.article-link')->each(function (Crawler $node) {
    $text = $node->text();
    $href = $node->attr('href');
    echo trim($text) . " -> " . $href . PHP_EOL;
});

로그인 후 세션 유지

로그인 페이지에서 세션 쿠키를 받아서 다른 페이지를 파싱할 때:

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use Symfony\Component\DomCrawler\Crawler;

// ① 쿠키 저장소 생성
$jar = new CookieJar();

// ② Guzzle 클라이언트 생성
$client = new Client([
    'cookies' => $jar, // 쿠키 자동 저장·전송
    'headers' => [
        'User-Agent' => 'MyScraperBot/1.0 (+https://example.com)',
    ],
]);

// ③ 로그인 요청 (예: POST로 ID/PW 전송)
$response = $client->post('https://example.com/login', [
    'form_params' => [
        'username' => 'myid',
        'password' => 'mypassword',
    ],
]);

echo "로그인 응답: " . $response->getStatusCode() . PHP_EOL;

// ④ 로그인 후 자동 저장된 쿠키 확인
print_r($jar->toArray());

// ⑤ 로그인된 상태로 보호된 페이지 요청
$response2 = $client->get('https://example.com/member/dashboard');
$html = (string) $response2->getBody();

// ⑥ DomCrawler 로 파싱
$crawler = new Crawler($html);
$title = $crawler->filter('title')->text();
echo "페이지 제목: {$title}" . PHP_EOL;
이렇게 하면 쿠키가 자동으로 Request/Response 간에 공유됩니다.
CookieJar를 같은 객체로 유지하면 여러 요청 간 로그인 상태가 이어집니다.

쿠키 파일로 저장하고 재사용하기


<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\FileCookieJar;

$cookieFile = __DIR__ . '/cookies.json';

// 파일 기반 쿠키 저장소
$jar = new FileCookieJar($cookieFile, true);

$client = new Client(['cookies' => $jar]);

// 로그인
$client->post('https://example.com/login', [
    'form_params' => ['username' => 'user', 'password' => 'pass']
]);

// 로그인된 상태로 접근
$res = $client->get('https://example.com/dashboard');
echo $res->getStatusCode();

// 스크립트 종료 시 쿠키 자동 저장

특정 쿠키를 수동으로 지정

이미 알고 있는 쿠키(예: 세션 토큰)를 직접 지정하려면:

// 특정 도메인 쿠키 수동 설정
$jar = CookieJar::fromArray([
    'PHPSESSID' => 'abc123xyz987',
], 'example.com');

데이터 전달

목적 Guzzle 옵션 결과
GET 쿼리스트링 전달 'query' => ['key' => 'value'] ?key=value
POST form 데이터 'form_params' => ['key' => 'value'] body=form
POST JSON 데이터 'json' => ['key' => 'value'] body={"key":"value"}
쿠키 유지 'cookies' => new CookieJar() 자동 저장/전송

댓글목록

등록된 댓글이 없습니다.

회원로그인

회원가입

사이트 정보

회사명 : 티로그 / 대표 : 김태규
주소 :부산광역시 수영구 광안로7번길 22 창성빌딩 3층
사업자 등록번호 : 617-86-10993
전화 : 051-325-6700 팩스 : 051-325-5665
통신판매업신고번호 : 제 2013-부산수영-0167 호
개인정보관리책임자 : 손승목

  • 게시물이 없습니다.

접속자집계

오늘
1,792
어제
2,676
최대
4,387
전체
468,521
Copyright © 소유하신 도메인. All rights reserved.