Skip to content

gracyvsgoutte

MIT 1 2 247
14.0 thousand (month) Feb 05 2023 1.34.0(2024-11-27 14:57:34 ago)
9,164 2 137 MIT
Dec 02 2012 8.5 thousand (month) v4.0.3(2023-04-01 09:05:33 ago)

Gracy is an API client library based on httpx that provides an extra stability layer with:

  • Retry logic
  • Logging
  • Connection throttling
  • Tracking/Middleware

In web scraping, Gracy can be a convenient tool for creating scraper based API clients.

Goutte is a screen scraping and web crawling library for PHP built on top of Symfony components (HttpClient, DomCrawler, BrowserKit). It provides a simple, elegant API for navigating websites, submitting forms, and extracting data.

Note: Goutte is deprecated as of 2023. Its functionality has been merged into Symfony's HttpBrowser component. For new projects, use Symfony HttpClient with DomCrawler directly. Goutte is still included here because it remains widely used in existing codebases and many tutorials reference it.

Key features include:

  • Simple scraping API Combines HTTP client and DOM crawler into a single interface. Navigate pages, click links, and extract content with a clean, chainable API.
  • CSS selector support Uses Symfony DomCrawler's filter() and each() methods with CSS selectors for extracting data from HTML.
  • Form handling Can find, fill in, and submit HTML forms. Handles all standard input types including file uploads.
  • Cookie management Automatically manages cookies across requests within a session.
  • Guzzle integration Uses Guzzle HTTP client under the hood for reliable HTTP communication with proxy support, authentication, and custom headers.
  • Link crawling Can follow links by text or CSS selector, making multi-page scraping straightforward.

For new PHP scraping projects, consider using Symfony HttpClient + DomCrawler directly, or the Roach framework for a more feature-complete solution.

Highlights


popularcss-selectors

Example Use


# 0. Import
import asyncio
from typing import Awaitable
from gracy import BaseEndpoint, Gracy, GracyConfig, LogEvent, LogLevel

# 1. Define your endpoints
class PokeApiEndpoint(BaseEndpoint):
    GET_POKEMON = "/pokemon/{NAME}" # 👈 Put placeholders as needed

# 2. Define your Graceful API
class GracefulPokeAPI(Gracy[str]):
    class Config:  # type: ignore
        BASE_URL = "https://pokeapi.co/api/v2/" # 👈 Optional BASE_URL
        # 👇 Define settings to apply for every request
        SETTINGS = GracyConfig(
          log_request=LogEvent(LogLevel.DEBUG),
          log_response=LogEvent(LogLevel.INFO, "{URL} took {ELAPSED}"),
          parser={
            "default": lambda r: r.json()
          }
        )

    async def get_pokemon(self, name: str) -> Awaitable[dict]:
        return await self.get(PokeApiEndpoint.GET_POKEMON, {"NAME": name})

    # Note: since Gracy is based on httpx we can customized the used client with custom headers etc"
    def _create_client(self) -> httpx.AsyncClient:
        client = super()._create_client()
        client.headers = {"User-Agent": f"My Scraper"} 
        return client

pokeapi = GracefulPokeAPI()

async def main():
    try:
      pokemon = await pokeapi.get_pokemon("pikachu")
      print(pokemon)

    finally:
        pokeapi.report_status("rich")


asyncio.run(main())
<?php
require 'vendor/autoload.php';

use Goutte\Client;

$client = new Client();

// Navigate to a page
$crawler = $client->request('GET', 'https://example.com');
echo $crawler->filter('title')->text();

// Extract data using CSS selectors
$crawler->filter('.product')->each(function ($node) {
    $name = $node->filter('.name')->text();
    $price = $node->filter('.price')->text();
    echo "$name: $price\n";
});

// Click a link
$link = $crawler->selectLink('Next Page')->link();
$crawler = $client->click($link);

// Fill in and submit a form
$crawler = $client->request('GET', 'https://example.com/login');
$form = $crawler->selectButton('Login')->form([
    'username' => 'user@example.com',
    'password' => 'password123',
]);
$crawler = $client->submit($form);

// Cookies are maintained automatically across requests
echo $crawler->filter('h1')->text(); // "Welcome back!"

Alternatives / Similar


Was this page helpful?