How to find HTML elements by attribute using DOM Crawler?

You can find HTML elements by attribute using
DOM Crawler
by utilizing the
filterXPath method
with an XPath selector that includes an attribute selector. Here’s an example that uses the filterXPath method with an XPath selector to find all input elements on
ScrapingBee’s login page
that have a type attribute equal to "email":

use SymfonyComponentDomCrawlerCrawler;
use GuzzleHttpClient;

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

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

// Find all input elements with a type attribute equal to "email"
$textInputs = $crawler->filterXPath('//input[@type="email"]');

// Loop over the inputs and print their values
foreach ($textInputs as $input) {
    echo $input->getAttribute('placeholder') . PHP_EOL;
}

// Output:
// Enter your email

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 *