How to select a link using its id or its label wit

2019-08-17 01:08发布

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?

3条回答
Fickle 薄情
2楼-- · 2019-08-17 01:25

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楼-- · 2019-08-17 01:29

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();
查看更多
够拽才男人
4楼-- · 2019-08-17 01:32

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

查看更多
登录 后发表回答