问题
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?
回答1:
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();
回答2:
Try this:
$myLink = $crawler->filter('#return-button')->text();
$myLink = $crawler->filter('.btn.return')->text();
This will return the link or button text, and then:
$crawler()->selectLink($myLink)->link();
This is indeed better than selecting links by text. Best of luck :-)
回答3:
I dont think so:
public selectLink ( string $value ) : Crawler
where the $value is a string that is the link text:
symfony.component.domcrawler/Crawler/selectLink
But you can try:
$crawler->filter('body')->children('a.lorem')->attr('href'); //if you need the link
or may, this is work with ids:
$crawler->filter('body')->children('a@foo');
You should figure out to yourself, if check this:
symfony/components/dom_crawler
来源:https://stackoverflow.com/questions/57397284/how-to-select-a-link-using-its-id-or-its-label-with-the-symfony-dom-crawler