10

This works

$this->assertEquals(1, $crawler->filter('.elementClass')->count()); // filter by class

But, this doesn't seem to work.

$this->assertEquals(1, $crawler->filter('#elementId')->count()); // filter by id

Any ideas?

Sukhrob
  • 901
  • 4
  • 12
  • 34

1 Answers1

12

Symfony2 DOM Crawler filter internally uses DOMXPath, so you can find answer for your question on this thread

query for filter should be something like(note that code bellow is untested, I'm sure link above will help you)

//*[@id='elementId']
Community
  • 1
  • 1
Igor
  • 1,835
  • 17
  • 15
  • Thank you for your answer. I used both filter() and filterXPath() methods. But, they didn't work. – Sukhrob Oct 29 '12 at 09:50
  • You have tried something like $crawler->filter('//yourtagname[@id="1"]')->count() and it didnt work? – Igor Oct 29 '12 at 09:54
  • By the way, I am filtering HTML, not XML. – Sukhrob Oct 29 '12 at 09:55
  • 1
    $crawler->filter('//yourtagname[@id="1"]')->count() shows error "Unexpected symbol". $crawler->filterXPath('//yourtagname[@id="1"]')->count() does not show error. But, it cannot find the element with id. – Sukhrob Oct 29 '12 at 10:00
  • Yup it seams that filter should work only for css selectors (https://github.com/symfony/DomCrawler/blob/master/Crawler.php) ** * Filters the list of nodes with a CSS selector. * * This method only works if you have installed the CssSelector Symfony Component. – Igor Oct 29 '12 at 10:05
  • I dont think filtering tags in HTML should be different than filtering XML tags. Maybe you can omit one / like "/yourtagname[@id='elementId']" . I can not try code on my machine right now, so i'm guessing – Igor Oct 29 '12 at 10:08
  • I installed CssSelector. Otherwise, my filter with class shouldn't have worked. – Sukhrob Oct 29 '12 at 10:10
  • Yeah I know that, I just copypasted more text then I should :) I just wanted to say that you should use filterXPath for your need. filter method is only for css – Igor Oct 29 '12 at 10:12
  • No, it didn't. It is really strange. – Sukhrob Oct 29 '12 at 10:13
  • You marked this answer as correct, do you solve problem and what is the final solution? – Igor Oct 29 '12 at 10:44
  • 3
    You were right. Even $this->assertEquals(1, $crawler->filter('#elementId')->count()); works. In my company, we use short open tags. I forgot to enable that. Thank you very much for your help, icrew. Beware, short open tags are bad :(. – Sukhrob Oct 29 '12 at 11:02