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

自作多情 提交于 2019-12-11 15:51:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!