How to find HTML elements by class with DOM Crawler?

You can find HTML elements by class with
DOM Crawler
by making use of the
filter method
with a [CSS selector](
CSS selectors
) that includes the class name. Here is some sample code that uses
Guzzle
to load
ScrapingBee’s homepage
and then uses the filter method to extract the tag with the class of mb-33:

use SymfonyComponentDomCrawlerCrawler;
use GuzzleHttpClient;

// Create a client to make the HTTP request
$client = new GuzzleHttpClient();
$response = $client->get('https://scrapingbee.com/');
$html = (string) $response->getBody();

// Load the HTML document
$crawler = new Crawler($html);

// Find all elements with the class "mb-33"
$h1Tag = $crawler->filter('.mb-33');

// Loop over the elements and print their text content
foreach ($h1Tag as $element) {
    echo $element->textContent . PHP_EOL;
}

// Output:
// Tired of getting blocked while scraping the web?
// Try ScrapingBee for Free

Note: This example uses Guzzle so you may have to install it.

Related DOM Crawler web scraping questions:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *