php Guzzle + Symfony DomCrawler 예제
페이지 정보

본문
설치
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를 같은 객체로 유지하면 여러 요청 간 로그인 상태가 이어집니다.
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() | 
      자동 저장/전송 | 
- 이전글리액트 강좌 링크 정보 25.10.22
 - 다음글sitemap.xml 에서 변경주기(<changefreq>)와 우선순위(<priority>) 태그 25.10.09
 
댓글목록
등록된 댓글이 없습니다.
