Symfony DomCrawler: Find element with specific attribute value

Wesley picture Wesley · Apr 30, 2013 · Viewed 43.1k times · Source

I'm using the DomCrawler component: http://symfony.com/doc/current/components/dom_crawler.html

I'd like to, using the CSS like syntax, get an element with a specific attribute value.

Here's the code I'm using:

$link = $crawler->filter('#product a[data-type="bla"]');

This seems to work, as the following returns 1:

echo count($link);

However, I can never not filter further than this. I can not do:

$link->filter('img')->attr('src'); 

This results in the following error message:

The current node list is empty.

However, I know for certain that it isn't.

I've tried the syntax on other elements and it's always the same. I am doing something wrong or is this not possible (with css like syntax, not xpath)

Answer

M8R-1jmw5r picture M8R-1jmw5r · Apr 30, 2013

I can not follow your problem. Using the current development versions (and also 2.1.0 and 2.2.0 versions) of the two software libraries dom-crawler and css-selector, the example code you provided works just fine considering the following example HTML:

<?php
use Symfony\Component\DomCrawler\Crawler;

// require dependencies here    

$html = <<<'HTML'
<!DOCTYPE html>
<html>
    <body>
        <p class="message">Hello World!</p>
        <p>Hello Crawler!</p>
        <div id="product">
            <a data-type="bla">
                <img src="OK">
            </a>
        </div>
    </body>
</html>
HTML;

$crawler = new Crawler($html);

$link = $crawler->filter('#product a[data-type="bla"]');

echo var_dump(count($link));

var_dump($link->filter('img')->attr('src'));

As you can see this is exactly your code (only a little different but essentially not), which gives the following output verbatim:

int(1)
string(2) "OK"

The first output line is the count() and the second is the src attribute value.

Have you run composer update? Have you double-checked the input?