phpsymfonysymfony4domcrawler

How to select a link using its id or its label with the symfony dom crawler?


Is it possible to select a link using its id or its class with the symfony crawler?

I tried:

$crawler()->selectLink('#return-button')->link();
$crawler()->selectLink('.btn.return')->link();

But I have the error:

InvalidArgumentException: The current node list is empty.

Does the selector only works using the content of the a tag?


Solution

  • Yes, it only works with the link text or alt attribute if your link is an image.

    The filter() method uses the CssSelector component to transform a selector into an XPath expression and then calls filterRelativeXPath() just as selectLink() does, so they return the same type and you should be able to just call

    $crawler->filter('#return-button')->link();
    

    In case of a class selector that returns multiple matches, since link() only works on the first node, you'll need to call links() instead:

    $crawler->filter('.btn.return')->links();