CrawlerTest.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DomCrawler\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\DomCrawler\Crawler;
  13. class CrawlerTest extends TestCase
  14. {
  15. public function testConstructor()
  16. {
  17. $crawler = new Crawler();
  18. $this->assertCount(0, $crawler, '__construct() returns an empty crawler');
  19. $doc = new \DOMDocument();
  20. $node = $doc->createElement('test');
  21. $crawler = new Crawler($node);
  22. $this->assertCount(1, $crawler, '__construct() takes a node as a first argument');
  23. }
  24. public function testGetUri()
  25. {
  26. $uri = 'http://symfony.com';
  27. $crawler = new Crawler(null, $uri);
  28. $this->assertEquals($uri, $crawler->getUri());
  29. }
  30. public function testGetBaseHref()
  31. {
  32. $baseHref = 'http://symfony.com';
  33. $crawler = new Crawler(null, null, $baseHref);
  34. $this->assertEquals($baseHref, $crawler->getBaseHref());
  35. }
  36. public function testAdd()
  37. {
  38. $crawler = new Crawler();
  39. $crawler->add($this->createDomDocument());
  40. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMDocument');
  41. $crawler = new Crawler();
  42. $crawler->add($this->createNodeList());
  43. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMNodeList');
  44. $list = [];
  45. foreach ($this->createNodeList() as $node) {
  46. $list[] = $node;
  47. }
  48. $crawler = new Crawler();
  49. $crawler->add($list);
  50. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from an array of nodes');
  51. $crawler = new Crawler();
  52. $crawler->add($this->createNodeList()->item(0));
  53. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMNode');
  54. $crawler = new Crawler();
  55. $crawler->add('<html><body>Foo</body></html>');
  56. $this->assertEquals('Foo', $crawler->filterXPath('//body')->text(), '->add() adds nodes from a string');
  57. }
  58. /**
  59. * @expectedException \InvalidArgumentException
  60. */
  61. public function testAddInvalidType()
  62. {
  63. $crawler = new Crawler();
  64. $crawler->add(1);
  65. }
  66. /**
  67. * @expectedException \InvalidArgumentException
  68. * @expectedExceptionMessage Attaching DOM nodes from multiple documents in the same crawler is forbidden.
  69. */
  70. public function testAddMultipleDocumentNode()
  71. {
  72. $crawler = $this->createTestCrawler();
  73. $crawler->addHtmlContent('<html><div class="foo"></html>', 'UTF-8');
  74. }
  75. public function testAddHtmlContent()
  76. {
  77. $crawler = new Crawler();
  78. $crawler->addHtmlContent('<html><div class="foo"></html>', 'UTF-8');
  79. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addHtmlContent() adds nodes from an HTML string');
  80. }
  81. public function testAddHtmlContentWithBaseTag()
  82. {
  83. $crawler = new Crawler();
  84. $crawler->addHtmlContent('<html><head><base href="http://symfony.com"></head><a href="/contact"></a></html>', 'UTF-8');
  85. $this->assertEquals('http://symfony.com', $crawler->filterXPath('//base')->attr('href'), '->addHtmlContent() adds nodes from an HTML string');
  86. $this->assertEquals('http://symfony.com/contact', $crawler->filterXPath('//a')->link()->getUri(), '->addHtmlContent() adds nodes from an HTML string');
  87. }
  88. /**
  89. * @requires extension mbstring
  90. */
  91. public function testAddHtmlContentCharset()
  92. {
  93. $crawler = new Crawler();
  94. $crawler->addHtmlContent('<html><div class="foo">Tiếng Việt</html>', 'UTF-8');
  95. $this->assertEquals('Tiếng Việt', $crawler->filterXPath('//div')->text());
  96. }
  97. public function testAddHtmlContentInvalidBaseTag()
  98. {
  99. $crawler = new Crawler(null, 'http://symfony.com');
  100. $crawler->addHtmlContent('<html><head><base target="_top"></head><a href="/contact"></a></html>', 'UTF-8');
  101. $this->assertEquals('http://symfony.com/contact', current($crawler->filterXPath('//a')->links())->getUri(), '->addHtmlContent() correctly handles a non-existent base tag href attribute');
  102. }
  103. public function testAddHtmlContentUnsupportedCharset()
  104. {
  105. $crawler = new Crawler();
  106. $crawler->addHtmlContent(file_get_contents(__DIR__.'/Fixtures/windows-1250.html'), 'Windows-1250');
  107. $this->assertEquals('Žťčýů', $crawler->filterXPath('//p')->text());
  108. }
  109. /**
  110. * @requires extension mbstring
  111. */
  112. public function testAddHtmlContentCharsetGbk()
  113. {
  114. $crawler = new Crawler();
  115. //gbk encode of <html><p>中文</p></html>
  116. $crawler->addHtmlContent(base64_decode('PGh0bWw+PHA+1tDOxDwvcD48L2h0bWw+'), 'gbk');
  117. $this->assertEquals('中文', $crawler->filterXPath('//p')->text());
  118. }
  119. public function testAddHtmlContentWithErrors()
  120. {
  121. $internalErrors = libxml_use_internal_errors(true);
  122. $crawler = new Crawler();
  123. $crawler->addHtmlContent(<<<'EOF'
  124. <!DOCTYPE html>
  125. <html>
  126. <head>
  127. </head>
  128. <body>
  129. <nav><a href="#"><a href="#"></nav>
  130. </body>
  131. </html>
  132. EOF
  133. , 'UTF-8');
  134. $errors = libxml_get_errors();
  135. $this->assertCount(1, $errors);
  136. $this->assertEquals("Tag nav invalid\n", $errors[0]->message);
  137. libxml_clear_errors();
  138. libxml_use_internal_errors($internalErrors);
  139. }
  140. public function testAddXmlContent()
  141. {
  142. $crawler = new Crawler();
  143. $crawler->addXmlContent('<html><div class="foo"></div></html>', 'UTF-8');
  144. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addXmlContent() adds nodes from an XML string');
  145. }
  146. public function testAddXmlContentCharset()
  147. {
  148. $crawler = new Crawler();
  149. $crawler->addXmlContent('<html><div class="foo">Tiếng Việt</div></html>', 'UTF-8');
  150. $this->assertEquals('Tiếng Việt', $crawler->filterXPath('//div')->text());
  151. }
  152. public function testAddXmlContentWithErrors()
  153. {
  154. $internalErrors = libxml_use_internal_errors(true);
  155. $crawler = new Crawler();
  156. $crawler->addXmlContent(<<<'EOF'
  157. <!DOCTYPE html>
  158. <html>
  159. <head>
  160. </head>
  161. <body>
  162. <nav><a href="#"><a href="#"></nav>
  163. </body>
  164. </html>
  165. EOF
  166. , 'UTF-8');
  167. $this->assertGreaterThan(1, libxml_get_errors());
  168. libxml_clear_errors();
  169. libxml_use_internal_errors($internalErrors);
  170. }
  171. public function testAddContent()
  172. {
  173. $crawler = new Crawler();
  174. $crawler->addContent('<html><div class="foo"></html>', 'text/html; charset=UTF-8');
  175. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an HTML string');
  176. $crawler = new Crawler();
  177. $crawler->addContent('<html><div class="foo"></html>', 'text/html; charset=UTF-8; dir=RTL');
  178. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an HTML string with extended content type');
  179. $crawler = new Crawler();
  180. $crawler->addContent('<html><div class="foo"></html>');
  181. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() uses text/html as the default type');
  182. $crawler = new Crawler();
  183. $crawler->addContent('<html><div class="foo"></div></html>', 'text/xml; charset=UTF-8');
  184. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an XML string');
  185. $crawler = new Crawler();
  186. $crawler->addContent('<html><div class="foo"></div></html>', 'text/xml');
  187. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an XML string');
  188. $crawler = new Crawler();
  189. $crawler->addContent('foo bar', 'text/plain');
  190. $this->assertCount(0, $crawler, '->addContent() does nothing if the type is not (x|ht)ml');
  191. $crawler = new Crawler();
  192. $crawler->addContent('<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><span>中文</span></html>');
  193. $this->assertEquals('中文', $crawler->filterXPath('//span')->text(), '->addContent() guess wrong charset');
  194. }
  195. /**
  196. * @requires extension iconv
  197. */
  198. public function testAddContentNonUtf8()
  199. {
  200. $crawler = new Crawler();
  201. $crawler->addContent(iconv('UTF-8', 'SJIS', '<html><head><meta charset="Shift_JIS"></head><body>日本語</body></html>'));
  202. $this->assertEquals('日本語', $crawler->filterXPath('//body')->text(), '->addContent() can recognize "Shift_JIS" in html5 meta charset tag');
  203. }
  204. public function testAddDocument()
  205. {
  206. $crawler = new Crawler();
  207. $crawler->addDocument($this->createDomDocument());
  208. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addDocument() adds nodes from a \DOMDocument');
  209. }
  210. public function testAddNodeList()
  211. {
  212. $crawler = new Crawler();
  213. $crawler->addNodeList($this->createNodeList());
  214. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNodeList() adds nodes from a \DOMNodeList');
  215. }
  216. public function testAddNodes()
  217. {
  218. $list = [];
  219. foreach ($this->createNodeList() as $node) {
  220. $list[] = $node;
  221. }
  222. $crawler = new Crawler();
  223. $crawler->addNodes($list);
  224. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNodes() adds nodes from an array of nodes');
  225. }
  226. public function testAddNode()
  227. {
  228. $crawler = new Crawler();
  229. $crawler->addNode($this->createNodeList()->item(0));
  230. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNode() adds nodes from a \DOMNode');
  231. }
  232. public function testClear()
  233. {
  234. $doc = new \DOMDocument();
  235. $node = $doc->createElement('test');
  236. $crawler = new Crawler($node);
  237. $crawler->clear();
  238. $this->assertCount(0, $crawler, '->clear() removes all the nodes from the crawler');
  239. }
  240. public function testEq()
  241. {
  242. $crawler = $this->createTestCrawler()->filterXPath('//li');
  243. $this->assertNotSame($crawler, $crawler->eq(0), '->eq() returns a new instance of a crawler');
  244. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->eq() returns a new instance of a crawler');
  245. $this->assertEquals('Two', $crawler->eq(1)->text(), '->eq() returns the nth node of the list');
  246. $this->assertCount(0, $crawler->eq(100), '->eq() returns an empty crawler if the nth node does not exist');
  247. }
  248. public function testEach()
  249. {
  250. $data = $this->createTestCrawler()->filterXPath('//ul[1]/li')->each(function ($node, $i) {
  251. return $i.'-'.$node->text();
  252. });
  253. $this->assertEquals(['0-One', '1-Two', '2-Three'], $data, '->each() executes an anonymous function on each node of the list');
  254. }
  255. public function testIteration()
  256. {
  257. $crawler = $this->createTestCrawler()->filterXPath('//li');
  258. $this->assertInstanceOf('Traversable', $crawler);
  259. $this->assertContainsOnlyInstancesOf('DOMElement', iterator_to_array($crawler), 'Iterating a Crawler gives DOMElement instances');
  260. }
  261. public function testSlice()
  262. {
  263. $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
  264. $this->assertNotSame($crawler->slice(), $crawler, '->slice() returns a new instance of a crawler');
  265. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler->slice(), '->slice() returns a new instance of a crawler');
  266. $this->assertCount(3, $crawler->slice(), '->slice() does not slice the nodes in the list if any param is entered');
  267. $this->assertCount(1, $crawler->slice(1, 1), '->slice() slices the nodes in the list');
  268. }
  269. public function testReduce()
  270. {
  271. $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
  272. $nodes = $crawler->reduce(function ($node, $i) {
  273. return 1 !== $i;
  274. });
  275. $this->assertNotSame($nodes, $crawler, '->reduce() returns a new instance of a crawler');
  276. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $nodes, '->reduce() returns a new instance of a crawler');
  277. $this->assertCount(2, $nodes, '->reduce() filters the nodes in the list');
  278. }
  279. public function testAttr()
  280. {
  281. $this->assertEquals('first', $this->createTestCrawler()->filterXPath('//li')->attr('class'), '->attr() returns the attribute of the first element of the node list');
  282. try {
  283. $this->createTestCrawler()->filterXPath('//ol')->attr('class');
  284. $this->fail('->attr() throws an \InvalidArgumentException if the node list is empty');
  285. } catch (\InvalidArgumentException $e) {
  286. $this->assertTrue(true, '->attr() throws an \InvalidArgumentException if the node list is empty');
  287. }
  288. }
  289. public function testMissingAttrValueIsNull()
  290. {
  291. $crawler = new Crawler();
  292. $crawler->addContent('<html><div non-empty-attr="sample value" empty-attr=""></div></html>', 'text/html; charset=UTF-8');
  293. $div = $crawler->filterXPath('//div');
  294. $this->assertEquals('sample value', $div->attr('non-empty-attr'), '->attr() reads non-empty attributes correctly');
  295. $this->assertEquals('', $div->attr('empty-attr'), '->attr() reads empty attributes correctly');
  296. $this->assertNull($div->attr('missing-attr'), '->attr() reads missing attributes correctly');
  297. }
  298. public function testNodeName()
  299. {
  300. $this->assertEquals('li', $this->createTestCrawler()->filterXPath('//li')->nodeName(), '->nodeName() returns the node name of the first element of the node list');
  301. try {
  302. $this->createTestCrawler()->filterXPath('//ol')->nodeName();
  303. $this->fail('->nodeName() throws an \InvalidArgumentException if the node list is empty');
  304. } catch (\InvalidArgumentException $e) {
  305. $this->assertTrue(true, '->nodeName() throws an \InvalidArgumentException if the node list is empty');
  306. }
  307. }
  308. public function testText()
  309. {
  310. $this->assertEquals('One', $this->createTestCrawler()->filterXPath('//li')->text(), '->text() returns the node value of the first element of the node list');
  311. try {
  312. $this->createTestCrawler()->filterXPath('//ol')->text();
  313. $this->fail('->text() throws an \InvalidArgumentException if the node list is empty');
  314. } catch (\InvalidArgumentException $e) {
  315. $this->assertTrue(true, '->text() throws an \InvalidArgumentException if the node list is empty');
  316. }
  317. }
  318. public function testHtml()
  319. {
  320. $this->assertEquals('<img alt="Bar">', $this->createTestCrawler()->filterXPath('//a[5]')->html());
  321. $this->assertEquals('<input type="text" value="TextValue" name="TextName"><input type="submit" value="FooValue" name="FooName" id="FooId"><input type="button" value="BarValue" name="BarName" id="BarId"><button value="ButtonValue" name="ButtonName" id="ButtonId"></button>', trim(preg_replace('~>\s+<~', '><', $this->createTestCrawler()->filterXPath('//form[@id="FooFormId"]')->html())));
  322. try {
  323. $this->createTestCrawler()->filterXPath('//ol')->html();
  324. $this->fail('->html() throws an \InvalidArgumentException if the node list is empty');
  325. } catch (\InvalidArgumentException $e) {
  326. $this->assertTrue(true, '->html() throws an \InvalidArgumentException if the node list is empty');
  327. }
  328. }
  329. public function testExtract()
  330. {
  331. $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
  332. $this->assertEquals(['One', 'Two', 'Three'], $crawler->extract('_text'), '->extract() returns an array of extracted data from the node list');
  333. $this->assertEquals([['One', 'first'], ['Two', ''], ['Three', '']], $crawler->extract(['_text', 'class']), '->extract() returns an array of extracted data from the node list');
  334. $this->assertEquals([[], [], []], $crawler->extract([]), '->extract() returns empty arrays if the attribute list is empty');
  335. $this->assertEquals([], $this->createTestCrawler()->filterXPath('//ol')->extract('_text'), '->extract() returns an empty array if the node list is empty');
  336. }
  337. public function testFilterXpathComplexQueries()
  338. {
  339. $crawler = $this->createTestCrawler()->filterXPath('//body');
  340. $this->assertCount(0, $crawler->filterXPath('/input'));
  341. $this->assertCount(0, $crawler->filterXPath('/body'));
  342. $this->assertCount(1, $crawler->filterXPath('./body'));
  343. $this->assertCount(1, $crawler->filterXPath('.//body'));
  344. $this->assertCount(5, $crawler->filterXPath('.//input'));
  345. $this->assertCount(4, $crawler->filterXPath('//form')->filterXPath('//button | //input'));
  346. $this->assertCount(1, $crawler->filterXPath('body'));
  347. $this->assertCount(6, $crawler->filterXPath('//button | //input'));
  348. $this->assertCount(1, $crawler->filterXPath('//body'));
  349. $this->assertCount(1, $crawler->filterXPath('descendant-or-self::body'));
  350. $this->assertCount(1, $crawler->filterXPath('//div[@id="parent"]')->filterXPath('./div'), 'A child selection finds only the current div');
  351. $this->assertCount(3, $crawler->filterXPath('//div[@id="parent"]')->filterXPath('descendant::div'), 'A descendant selector matches the current div and its child');
  352. $this->assertCount(3, $crawler->filterXPath('//div[@id="parent"]')->filterXPath('//div'), 'A descendant selector matches the current div and its child');
  353. $this->assertCount(5, $crawler->filterXPath('(//a | //div)//img'));
  354. $this->assertCount(7, $crawler->filterXPath('((//a | //div)//img | //ul)'));
  355. $this->assertCount(7, $crawler->filterXPath('( ( //a | //div )//img | //ul )'));
  356. $this->assertCount(1, $crawler->filterXPath("//a[./@href][((./@id = 'Klausi|Claudiu' or normalize-space(string(.)) = 'Klausi|Claudiu' or ./@title = 'Klausi|Claudiu' or ./@rel = 'Klausi|Claudiu') or .//img[./@alt = 'Klausi|Claudiu'])]"));
  357. }
  358. public function testFilterXPath()
  359. {
  360. $crawler = $this->createTestCrawler();
  361. $this->assertNotSame($crawler, $crawler->filterXPath('//li'), '->filterXPath() returns a new instance of a crawler');
  362. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->filterXPath() returns a new instance of a crawler');
  363. $crawler = $this->createTestCrawler()->filterXPath('//ul');
  364. $this->assertCount(6, $crawler->filterXPath('//li'), '->filterXPath() filters the node list with the XPath expression');
  365. $crawler = $this->createTestCrawler();
  366. $this->assertCount(3, $crawler->filterXPath('//body')->filterXPath('//button')->parents(), '->filterXpath() preserves parents when chained');
  367. }
  368. public function testFilterRemovesDuplicates()
  369. {
  370. $crawler = $this->createTestCrawler()->filter('html, body')->filter('li');
  371. $this->assertCount(6, $crawler, 'The crawler removes duplicates when filtering.');
  372. }
  373. public function testFilterXPathWithDefaultNamespace()
  374. {
  375. $crawler = $this->createTestXmlCrawler()->filterXPath('//default:entry/default:id');
  376. $this->assertCount(1, $crawler, '->filterXPath() automatically registers a namespace');
  377. $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text());
  378. }
  379. public function testFilterXPathWithCustomDefaultNamespace()
  380. {
  381. $crawler = $this->createTestXmlCrawler();
  382. $crawler->setDefaultNamespacePrefix('x');
  383. $crawler = $crawler->filterXPath('//x:entry/x:id');
  384. $this->assertCount(1, $crawler, '->filterXPath() lets to override the default namespace prefix');
  385. $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text());
  386. }
  387. public function testFilterXPathWithNamespace()
  388. {
  389. $crawler = $this->createTestXmlCrawler()->filterXPath('//yt:accessControl');
  390. $this->assertCount(2, $crawler, '->filterXPath() automatically registers a namespace');
  391. }
  392. public function testFilterXPathWithMultipleNamespaces()
  393. {
  394. $crawler = $this->createTestXmlCrawler()->filterXPath('//media:group/yt:aspectRatio');
  395. $this->assertCount(1, $crawler, '->filterXPath() automatically registers multiple namespaces');
  396. $this->assertSame('widescreen', $crawler->text());
  397. }
  398. public function testFilterXPathWithManuallyRegisteredNamespace()
  399. {
  400. $crawler = $this->createTestXmlCrawler();
  401. $crawler->registerNamespace('m', 'http://search.yahoo.com/mrss/');
  402. $crawler = $crawler->filterXPath('//m:group/yt:aspectRatio');
  403. $this->assertCount(1, $crawler, '->filterXPath() uses manually registered namespace');
  404. $this->assertSame('widescreen', $crawler->text());
  405. }
  406. public function testFilterXPathWithAnUrl()
  407. {
  408. $crawler = $this->createTestXmlCrawler();
  409. $crawler = $crawler->filterXPath('//media:category[@scheme="http://gdata.youtube.com/schemas/2007/categories.cat"]');
  410. $this->assertCount(1, $crawler);
  411. $this->assertSame('Music', $crawler->text());
  412. }
  413. public function testFilterXPathWithFakeRoot()
  414. {
  415. $crawler = $this->createTestCrawler();
  416. $this->assertCount(0, $crawler->filterXPath('.'), '->filterXPath() returns an empty result if the XPath references the fake root node');
  417. $this->assertCount(0, $crawler->filterXPath('self::*'), '->filterXPath() returns an empty result if the XPath references the fake root node');
  418. $this->assertCount(0, $crawler->filterXPath('self::_root'), '->filterXPath() returns an empty result if the XPath references the fake root node');
  419. }
  420. public function testFilterXPathWithAncestorAxis()
  421. {
  422. $crawler = $this->createTestCrawler()->filterXPath('//form');
  423. $this->assertCount(0, $crawler->filterXPath('ancestor::*'), 'The fake root node has no ancestor nodes');
  424. }
  425. public function testFilterXPathWithAncestorOrSelfAxis()
  426. {
  427. $crawler = $this->createTestCrawler()->filterXPath('//form');
  428. $this->assertCount(0, $crawler->filterXPath('ancestor-or-self::*'), 'The fake root node has no ancestor nodes');
  429. }
  430. public function testFilterXPathWithAttributeAxis()
  431. {
  432. $crawler = $this->createTestCrawler()->filterXPath('//form');
  433. $this->assertCount(0, $crawler->filterXPath('attribute::*'), 'The fake root node has no attribute nodes');
  434. }
  435. public function testFilterXPathWithAttributeAxisAfterElementAxis()
  436. {
  437. $this->assertCount(3, $this->createTestCrawler()->filterXPath('//form/button/attribute::*'), '->filterXPath() handles attribute axes properly when they are preceded by an element filtering axis');
  438. }
  439. public function testFilterXPathWithChildAxis()
  440. {
  441. $crawler = $this->createTestCrawler()->filterXPath('//div[@id="parent"]');
  442. $this->assertCount(1, $crawler->filterXPath('child::div'), 'A child selection finds only the current div');
  443. }
  444. public function testFilterXPathWithFollowingAxis()
  445. {
  446. $crawler = $this->createTestCrawler()->filterXPath('//a');
  447. $this->assertCount(0, $crawler->filterXPath('following::div'), 'The fake root node has no following nodes');
  448. }
  449. public function testFilterXPathWithFollowingSiblingAxis()
  450. {
  451. $crawler = $this->createTestCrawler()->filterXPath('//a');
  452. $this->assertCount(0, $crawler->filterXPath('following-sibling::div'), 'The fake root node has no following nodes');
  453. }
  454. public function testFilterXPathWithNamespaceAxis()
  455. {
  456. $crawler = $this->createTestCrawler()->filterXPath('//button');
  457. $this->assertCount(0, $crawler->filterXPath('namespace::*'), 'The fake root node has no namespace nodes');
  458. }
  459. public function testFilterXPathWithNamespaceAxisAfterElementAxis()
  460. {
  461. $crawler = $this->createTestCrawler()->filterXPath('//div[@id="parent"]/namespace::*');
  462. $this->assertCount(0, $crawler->filterXPath('namespace::*'), 'Namespace axes cannot be requested');
  463. }
  464. public function testFilterXPathWithParentAxis()
  465. {
  466. $crawler = $this->createTestCrawler()->filterXPath('//button');
  467. $this->assertCount(0, $crawler->filterXPath('parent::*'), 'The fake root node has no parent nodes');
  468. }
  469. public function testFilterXPathWithPrecedingAxis()
  470. {
  471. $crawler = $this->createTestCrawler()->filterXPath('//form');
  472. $this->assertCount(0, $crawler->filterXPath('preceding::*'), 'The fake root node has no preceding nodes');
  473. }
  474. public function testFilterXPathWithPrecedingSiblingAxis()
  475. {
  476. $crawler = $this->createTestCrawler()->filterXPath('//form');
  477. $this->assertCount(0, $crawler->filterXPath('preceding-sibling::*'), 'The fake root node has no preceding nodes');
  478. }
  479. public function testFilterXPathWithSelfAxes()
  480. {
  481. $crawler = $this->createTestCrawler()->filterXPath('//a');
  482. $this->assertCount(0, $crawler->filterXPath('self::a'), 'The fake root node has no "real" element name');
  483. $this->assertCount(0, $crawler->filterXPath('self::a/img'), 'The fake root node has no "real" element name');
  484. $this->assertCount(10, $crawler->filterXPath('self::*/a'));
  485. }
  486. public function testFilter()
  487. {
  488. $crawler = $this->createTestCrawler();
  489. $this->assertNotSame($crawler, $crawler->filter('li'), '->filter() returns a new instance of a crawler');
  490. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->filter() returns a new instance of a crawler');
  491. $crawler = $this->createTestCrawler()->filter('ul');
  492. $this->assertCount(6, $crawler->filter('li'), '->filter() filters the node list with the CSS selector');
  493. }
  494. public function testFilterWithDefaultNamespace()
  495. {
  496. $crawler = $this->createTestXmlCrawler()->filter('default|entry default|id');
  497. $this->assertCount(1, $crawler, '->filter() automatically registers namespaces');
  498. $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text());
  499. }
  500. public function testFilterWithNamespace()
  501. {
  502. $crawler = $this->createTestXmlCrawler()->filter('yt|accessControl');
  503. $this->assertCount(2, $crawler, '->filter() automatically registers namespaces');
  504. }
  505. public function testFilterWithMultipleNamespaces()
  506. {
  507. $crawler = $this->createTestXmlCrawler()->filter('media|group yt|aspectRatio');
  508. $this->assertCount(1, $crawler, '->filter() automatically registers namespaces');
  509. $this->assertSame('widescreen', $crawler->text());
  510. }
  511. public function testFilterWithDefaultNamespaceOnly()
  512. {
  513. $crawler = new Crawler('<?xml version="1.0" encoding="UTF-8"?>
  514. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  515. <url>
  516. <loc>http://localhost/foo</loc>
  517. <changefreq>weekly</changefreq>
  518. <priority>0.5</priority>
  519. <lastmod>2012-11-16</lastmod>
  520. </url>
  521. <url>
  522. <loc>http://localhost/bar</loc>
  523. <changefreq>weekly</changefreq>
  524. <priority>0.5</priority>
  525. <lastmod>2012-11-16</lastmod>
  526. </url>
  527. </urlset>
  528. ');
  529. $this->assertEquals(2, $crawler->filter('url')->count());
  530. }
  531. public function testSelectLink()
  532. {
  533. $crawler = $this->createTestCrawler();
  534. $this->assertNotSame($crawler, $crawler->selectLink('Foo'), '->selectLink() returns a new instance of a crawler');
  535. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectLink() returns a new instance of a crawler');
  536. $this->assertCount(1, $crawler->selectLink('Fabien\'s Foo'), '->selectLink() selects links by the node values');
  537. $this->assertCount(1, $crawler->selectLink('Fabien\'s Bar'), '->selectLink() selects links by the alt attribute of a clickable image');
  538. $this->assertCount(2, $crawler->selectLink('Fabien"s Foo'), '->selectLink() selects links by the node values');
  539. $this->assertCount(2, $crawler->selectLink('Fabien"s Bar'), '->selectLink() selects links by the alt attribute of a clickable image');
  540. $this->assertCount(1, $crawler->selectLink('\' Fabien"s Foo'), '->selectLink() selects links by the node values');
  541. $this->assertCount(1, $crawler->selectLink('\' Fabien"s Bar'), '->selectLink() selects links by the alt attribute of a clickable image');
  542. $this->assertCount(4, $crawler->selectLink('Foo'), '->selectLink() selects links by the node values');
  543. $this->assertCount(4, $crawler->selectLink('Bar'), '->selectLink() selects links by the node values');
  544. }
  545. public function testSelectImage()
  546. {
  547. $crawler = $this->createTestCrawler();
  548. $this->assertNotSame($crawler, $crawler->selectImage('Bar'), '->selectImage() returns a new instance of a crawler');
  549. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectImage() returns a new instance of a crawler');
  550. $this->assertCount(1, $crawler->selectImage('Fabien\'s Bar'), '->selectImage() selects images by alt attribute');
  551. $this->assertCount(2, $crawler->selectImage('Fabien"s Bar'), '->selectImage() selects images by alt attribute');
  552. $this->assertCount(1, $crawler->selectImage('\' Fabien"s Bar'), '->selectImage() selects images by alt attribute');
  553. }
  554. public function testSelectButton()
  555. {
  556. $crawler = $this->createTestCrawler();
  557. $this->assertNotSame($crawler, $crawler->selectButton('FooValue'), '->selectButton() returns a new instance of a crawler');
  558. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectButton() returns a new instance of a crawler');
  559. $this->assertEquals(1, $crawler->selectButton('FooValue')->count(), '->selectButton() selects buttons');
  560. $this->assertEquals(1, $crawler->selectButton('FooName')->count(), '->selectButton() selects buttons');
  561. $this->assertEquals(1, $crawler->selectButton('FooId')->count(), '->selectButton() selects buttons');
  562. $this->assertEquals(1, $crawler->selectButton('BarValue')->count(), '->selectButton() selects buttons');
  563. $this->assertEquals(1, $crawler->selectButton('BarName')->count(), '->selectButton() selects buttons');
  564. $this->assertEquals(1, $crawler->selectButton('BarId')->count(), '->selectButton() selects buttons');
  565. $this->assertEquals(1, $crawler->selectButton('FooBarValue')->count(), '->selectButton() selects buttons with form attribute too');
  566. $this->assertEquals(1, $crawler->selectButton('FooBarName')->count(), '->selectButton() selects buttons with form attribute too');
  567. }
  568. public function testSelectButtonWithSingleQuotesInNameAttribute()
  569. {
  570. $html = <<<'HTML'
  571. <!DOCTYPE html>
  572. <html lang="en">
  573. <body>
  574. <div id="action">
  575. <a href="/index.php?r=site/login">Login</a>
  576. </div>
  577. <form id="login-form" action="/index.php?r=site/login" method="post">
  578. <button type="submit" name="Click 'Here'">Submit</button>
  579. </form>
  580. </body>
  581. </html>
  582. HTML;
  583. $crawler = new Crawler($html);
  584. $this->assertCount(1, $crawler->selectButton('Click \'Here\''));
  585. }
  586. public function testSelectButtonWithDoubleQuotesInNameAttribute()
  587. {
  588. $html = <<<'HTML'
  589. <!DOCTYPE html>
  590. <html lang="en">
  591. <body>
  592. <div id="action">
  593. <a href="/index.php?r=site/login">Login</a>
  594. </div>
  595. <form id="login-form" action="/index.php?r=site/login" method="post">
  596. <button type="submit" name='Click "Here"'>Submit</button>
  597. </form>
  598. </body>
  599. </html>
  600. HTML;
  601. $crawler = new Crawler($html);
  602. $this->assertCount(1, $crawler->selectButton('Click "Here"'));
  603. }
  604. public function testLink()
  605. {
  606. $crawler = $this->createTestCrawler('http://example.com/bar/')->selectLink('Foo');
  607. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Link', $crawler->link(), '->link() returns a Link instance');
  608. $this->assertEquals('POST', $crawler->link('post')->getMethod(), '->link() takes a method as its argument');
  609. $crawler = $this->createTestCrawler('http://example.com/bar')->selectLink('GetLink');
  610. $this->assertEquals('http://example.com/bar?get=param', $crawler->link()->getUri(), '->link() returns a Link instance');
  611. try {
  612. $this->createTestCrawler()->filterXPath('//ol')->link();
  613. $this->fail('->link() throws an \InvalidArgumentException if the node list is empty');
  614. } catch (\InvalidArgumentException $e) {
  615. $this->assertTrue(true, '->link() throws an \InvalidArgumentException if the node list is empty');
  616. }
  617. }
  618. /**
  619. * @expectedException \InvalidArgumentException
  620. * @expectedExceptionMessage The selected node should be instance of DOMElement
  621. */
  622. public function testInvalidLink()
  623. {
  624. $crawler = $this->createTestCrawler('http://example.com/bar/');
  625. $crawler->filterXPath('//li/text()')->link();
  626. }
  627. /**
  628. * @expectedException \InvalidArgumentException
  629. * @expectedExceptionMessage The selected node should be instance of DOMElement
  630. */
  631. public function testInvalidLinks()
  632. {
  633. $crawler = $this->createTestCrawler('http://example.com/bar/');
  634. $crawler->filterXPath('//li/text()')->link();
  635. }
  636. public function testImage()
  637. {
  638. $crawler = $this->createTestCrawler('http://example.com/bar/')->selectImage('Bar');
  639. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Image', $crawler->image(), '->image() returns an Image instance');
  640. try {
  641. $this->createTestCrawler()->filterXPath('//ol')->image();
  642. $this->fail('->image() throws an \InvalidArgumentException if the node list is empty');
  643. } catch (\InvalidArgumentException $e) {
  644. $this->assertTrue(true, '->image() throws an \InvalidArgumentException if the node list is empty');
  645. }
  646. }
  647. public function testSelectLinkAndLinkFiltered()
  648. {
  649. $html = <<<'HTML'
  650. <!DOCTYPE html>
  651. <html lang="en">
  652. <body>
  653. <div id="action">
  654. <a href="/index.php?r=site/login">Login</a>
  655. </div>
  656. <form id="login-form" action="/index.php?r=site/login" method="post">
  657. <button type="submit">Submit</button>
  658. </form>
  659. </body>
  660. </html>
  661. HTML;
  662. $crawler = new Crawler($html);
  663. $filtered = $crawler->filterXPath("descendant-or-self::*[@id = 'login-form']");
  664. $this->assertCount(0, $filtered->selectLink('Login'));
  665. $this->assertCount(1, $filtered->selectButton('Submit'));
  666. $filtered = $crawler->filterXPath("descendant-or-self::*[@id = 'action']");
  667. $this->assertCount(1, $filtered->selectLink('Login'));
  668. $this->assertCount(0, $filtered->selectButton('Submit'));
  669. $this->assertCount(1, $crawler->selectLink('Login')->selectLink('Login'));
  670. $this->assertCount(1, $crawler->selectButton('Submit')->selectButton('Submit'));
  671. }
  672. public function testChaining()
  673. {
  674. $crawler = new Crawler('<div name="a"><div name="b"><div name="c"></div></div></div>');
  675. $this->assertEquals('a', $crawler->filterXPath('//div')->filterXPath('div')->filterXPath('div')->attr('name'));
  676. }
  677. public function testLinks()
  678. {
  679. $crawler = $this->createTestCrawler('http://example.com/bar/')->selectLink('Foo');
  680. $this->assertInternalType('array', $crawler->links(), '->links() returns an array');
  681. $this->assertCount(4, $crawler->links(), '->links() returns an array');
  682. $links = $crawler->links();
  683. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Link', $links[0], '->links() returns an array of Link instances');
  684. $this->assertEquals([], $this->createTestCrawler()->filterXPath('//ol')->links(), '->links() returns an empty array if the node selection is empty');
  685. }
  686. public function testImages()
  687. {
  688. $crawler = $this->createTestCrawler('http://example.com/bar/')->selectImage('Bar');
  689. $this->assertInternalType('array', $crawler->images(), '->images() returns an array');
  690. $this->assertCount(4, $crawler->images(), '->images() returns an array');
  691. $images = $crawler->images();
  692. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Image', $images[0], '->images() returns an array of Image instances');
  693. $this->assertEquals([], $this->createTestCrawler()->filterXPath('//ol')->links(), '->links() returns an empty array if the node selection is empty');
  694. }
  695. public function testForm()
  696. {
  697. $testCrawler = $this->createTestCrawler('http://example.com/bar/');
  698. $crawler = $testCrawler->selectButton('FooValue');
  699. $crawler2 = $testCrawler->selectButton('FooBarValue');
  700. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Form', $crawler->form(), '->form() returns a Form instance');
  701. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Form', $crawler2->form(), '->form() returns a Form instance');
  702. $this->assertEquals($crawler->form()->getFormNode()->getAttribute('id'), $crawler2->form()->getFormNode()->getAttribute('id'), '->form() works on elements with form attribute');
  703. $this->assertEquals(['FooName' => 'FooBar', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'], $crawler->form(['FooName' => 'FooBar'])->getValues(), '->form() takes an array of values to submit as its first argument');
  704. $this->assertEquals(['FooName' => 'FooValue', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'], $crawler->form()->getValues(), '->getValues() returns correct form values');
  705. $this->assertEquals(['FooBarName' => 'FooBarValue', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'], $crawler2->form()->getValues(), '->getValues() returns correct form values');
  706. try {
  707. $this->createTestCrawler()->filterXPath('//ol')->form();
  708. $this->fail('->form() throws an \InvalidArgumentException if the node list is empty');
  709. } catch (\InvalidArgumentException $e) {
  710. $this->assertTrue(true, '->form() throws an \InvalidArgumentException if the node list is empty');
  711. }
  712. }
  713. /**
  714. * @expectedException \InvalidArgumentException
  715. * @expectedExceptionMessage The selected node should be instance of DOMElement
  716. */
  717. public function testInvalidForm()
  718. {
  719. $crawler = $this->createTestCrawler('http://example.com/bar/');
  720. $crawler->filterXPath('//li/text()')->form();
  721. }
  722. public function testLast()
  723. {
  724. $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
  725. $this->assertNotSame($crawler, $crawler->last(), '->last() returns a new instance of a crawler');
  726. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->last() returns a new instance of a crawler');
  727. $this->assertEquals('Three', $crawler->last()->text());
  728. }
  729. public function testFirst()
  730. {
  731. $crawler = $this->createTestCrawler()->filterXPath('//li');
  732. $this->assertNotSame($crawler, $crawler->first(), '->first() returns a new instance of a crawler');
  733. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->first() returns a new instance of a crawler');
  734. $this->assertEquals('One', $crawler->first()->text());
  735. }
  736. public function testSiblings()
  737. {
  738. $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(1);
  739. $this->assertNotSame($crawler, $crawler->siblings(), '->siblings() returns a new instance of a crawler');
  740. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->siblings() returns a new instance of a crawler');
  741. $nodes = $crawler->siblings();
  742. $this->assertEquals(2, $nodes->count());
  743. $this->assertEquals('One', $nodes->eq(0)->text());
  744. $this->assertEquals('Three', $nodes->eq(1)->text());
  745. $nodes = $this->createTestCrawler()->filterXPath('//li')->eq(0)->siblings();
  746. $this->assertEquals(2, $nodes->count());
  747. $this->assertEquals('Two', $nodes->eq(0)->text());
  748. $this->assertEquals('Three', $nodes->eq(1)->text());
  749. try {
  750. $this->createTestCrawler()->filterXPath('//ol')->siblings();
  751. $this->fail('->siblings() throws an \InvalidArgumentException if the node list is empty');
  752. } catch (\InvalidArgumentException $e) {
  753. $this->assertTrue(true, '->siblings() throws an \InvalidArgumentException if the node list is empty');
  754. }
  755. }
  756. public function testNextAll()
  757. {
  758. $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(1);
  759. $this->assertNotSame($crawler, $crawler->nextAll(), '->nextAll() returns a new instance of a crawler');
  760. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->nextAll() returns a new instance of a crawler');
  761. $nodes = $crawler->nextAll();
  762. $this->assertEquals(1, $nodes->count());
  763. $this->assertEquals('Three', $nodes->eq(0)->text());
  764. try {
  765. $this->createTestCrawler()->filterXPath('//ol')->nextAll();
  766. $this->fail('->nextAll() throws an \InvalidArgumentException if the node list is empty');
  767. } catch (\InvalidArgumentException $e) {
  768. $this->assertTrue(true, '->nextAll() throws an \InvalidArgumentException if the node list is empty');
  769. }
  770. }
  771. public function testPreviousAll()
  772. {
  773. $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(2);
  774. $this->assertNotSame($crawler, $crawler->previousAll(), '->previousAll() returns a new instance of a crawler');
  775. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->previousAll() returns a new instance of a crawler');
  776. $nodes = $crawler->previousAll();
  777. $this->assertEquals(2, $nodes->count());
  778. $this->assertEquals('Two', $nodes->eq(0)->text());
  779. try {
  780. $this->createTestCrawler()->filterXPath('//ol')->previousAll();
  781. $this->fail('->previousAll() throws an \InvalidArgumentException if the node list is empty');
  782. } catch (\InvalidArgumentException $e) {
  783. $this->assertTrue(true, '->previousAll() throws an \InvalidArgumentException if the node list is empty');
  784. }
  785. }
  786. public function testChildren()
  787. {
  788. $crawler = $this->createTestCrawler()->filterXPath('//ul');
  789. $this->assertNotSame($crawler, $crawler->children(), '->children() returns a new instance of a crawler');
  790. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->children() returns a new instance of a crawler');
  791. $nodes = $crawler->children();
  792. $this->assertEquals(3, $nodes->count());
  793. $this->assertEquals('One', $nodes->eq(0)->text());
  794. $this->assertEquals('Two', $nodes->eq(1)->text());
  795. $this->assertEquals('Three', $nodes->eq(2)->text());
  796. try {
  797. $this->createTestCrawler()->filterXPath('//ol')->children();
  798. $this->fail('->children() throws an \InvalidArgumentException if the node list is empty');
  799. } catch (\InvalidArgumentException $e) {
  800. $this->assertTrue(true, '->children() throws an \InvalidArgumentException if the node list is empty');
  801. }
  802. try {
  803. $crawler = new Crawler('<p></p>');
  804. $crawler->filter('p')->children();
  805. $this->assertTrue(true, '->children() does not trigger a notice if the node has no children');
  806. } catch (\PHPUnit\Framework\Error\Notice $e) {
  807. $this->fail('->children() does not trigger a notice if the node has no children');
  808. } catch (\PHPUnit_Framework_Error_Notice $e) {
  809. $this->fail('->children() does not trigger a notice if the node has no children');
  810. }
  811. }
  812. public function testParents()
  813. {
  814. $crawler = $this->createTestCrawler()->filterXPath('//li[1]');
  815. $this->assertNotSame($crawler, $crawler->parents(), '->parents() returns a new instance of a crawler');
  816. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->parents() returns a new instance of a crawler');
  817. $nodes = $crawler->parents();
  818. $this->assertEquals(3, $nodes->count());
  819. $nodes = $this->createTestCrawler()->filterXPath('//html')->parents();
  820. $this->assertEquals(0, $nodes->count());
  821. try {
  822. $this->createTestCrawler()->filterXPath('//ol')->parents();
  823. $this->fail('->parents() throws an \InvalidArgumentException if the node list is empty');
  824. } catch (\InvalidArgumentException $e) {
  825. $this->assertTrue(true, '->parents() throws an \InvalidArgumentException if the node list is empty');
  826. }
  827. }
  828. /**
  829. * @dataProvider getBaseTagData
  830. */
  831. public function testBaseTag($baseValue, $linkValue, $expectedUri, $currentUri = null, $description = '')
  832. {
  833. $crawler = new Crawler('<html><base href="'.$baseValue.'"><a href="'.$linkValue.'"></a></html>', $currentUri);
  834. $this->assertEquals($expectedUri, $crawler->filterXPath('//a')->link()->getUri(), $description);
  835. }
  836. public function getBaseTagData()
  837. {
  838. return [
  839. ['http://base.com', 'link', 'http://base.com/link'],
  840. ['//base.com', 'link', 'https://base.com/link', 'https://domain.com', '<base> tag can use a schema-less URL'],
  841. ['path/', 'link', 'https://domain.com/path/link', 'https://domain.com', '<base> tag can set a path'],
  842. ['http://base.com', '#', 'http://base.com#', 'http://domain.com/path/link', '<base> tag does work with links to an anchor'],
  843. ['http://base.com', '', 'http://base.com', 'http://domain.com/path/link', '<base> tag does work with empty links'],
  844. ];
  845. }
  846. /**
  847. * @dataProvider getBaseTagWithFormData
  848. */
  849. public function testBaseTagWithForm($baseValue, $actionValue, $expectedUri, $currentUri = null, $description = null)
  850. {
  851. $crawler = new Crawler('<html><base href="'.$baseValue.'"><form method="post" action="'.$actionValue.'"><button type="submit" name="submit"/></form></html>', $currentUri);
  852. $this->assertEquals($expectedUri, $crawler->filterXPath('//button')->form()->getUri(), $description);
  853. }
  854. public function getBaseTagWithFormData()
  855. {
  856. return [
  857. ['https://base.com/', 'link/', 'https://base.com/link/', 'https://base.com/link/', '<base> tag does work with a path and relative form action'],
  858. ['/basepath', '/registration', 'http://domain.com/registration', 'http://domain.com/registration', '<base> tag does work with a path and form action'],
  859. ['/basepath', '', 'http://domain.com/registration', 'http://domain.com/registration', '<base> tag does work with a path and empty form action'],
  860. ['http://base.com/', '/registration', 'http://base.com/registration', 'http://domain.com/registration', '<base> tag does work with a URL and form action'],
  861. ['http://base.com', '', 'http://domain.com/path/form', 'http://domain.com/path/form', '<base> tag does work with a URL and an empty form action'],
  862. ['http://base.com/path', '/registration', 'http://base.com/registration', 'http://domain.com/path/form', '<base> tag does work with a URL and form action'],
  863. ];
  864. }
  865. public function testCountOfNestedElements()
  866. {
  867. $crawler = new Crawler('<html><body><ul><li>List item 1<ul><li>Sublist item 1</li><li>Sublist item 2</ul></li></ul></body></html>');
  868. $this->assertCount(1, $crawler->filter('li:contains("List item 1")'));
  869. }
  870. public function testEvaluateReturnsTypedResultOfXPathExpressionOnADocumentSubset()
  871. {
  872. $crawler = $this->createTestCrawler();
  873. $result = $crawler->filterXPath('//form/input')->evaluate('substring-before(@name, "Name")');
  874. $this->assertSame(['Text', 'Foo', 'Bar'], $result);
  875. }
  876. public function testEvaluateReturnsTypedResultOfNamespacedXPathExpressionOnADocumentSubset()
  877. {
  878. $crawler = $this->createTestXmlCrawler();
  879. $result = $crawler->filterXPath('//yt:accessControl/@action')->evaluate('string(.)');
  880. $this->assertSame(['comment', 'videoRespond'], $result);
  881. }
  882. public function testEvaluateReturnsTypedResultOfNamespacedXPathExpression()
  883. {
  884. $crawler = $this->createTestXmlCrawler();
  885. $crawler->registerNamespace('youtube', 'http://gdata.youtube.com/schemas/2007');
  886. $result = $crawler->evaluate('string(//youtube:accessControl/@action)');
  887. $this->assertSame(['comment'], $result);
  888. }
  889. public function testEvaluateReturnsACrawlerIfXPathExpressionEvaluatesToANode()
  890. {
  891. $crawler = $this->createTestCrawler()->evaluate('//form/input[1]');
  892. $this->assertInstanceOf(Crawler::class, $crawler);
  893. $this->assertCount(1, $crawler);
  894. $this->assertSame('input', $crawler->first()->nodeName());
  895. }
  896. /**
  897. * @expectedException \LogicException
  898. */
  899. public function testEvaluateThrowsAnExceptionIfDocumentIsEmpty()
  900. {
  901. (new Crawler())->evaluate('//form/input[1]');
  902. }
  903. public function createTestCrawler($uri = null)
  904. {
  905. $dom = new \DOMDocument();
  906. $dom->loadHTML('
  907. <html>
  908. <body>
  909. <a href="foo">Foo</a>
  910. <a href="/foo"> Fabien\'s Foo </a>
  911. <a href="/foo">Fabien"s Foo</a>
  912. <a href="/foo">\' Fabien"s Foo</a>
  913. <a href="/bar"><img alt="Bar"/></a>
  914. <a href="/bar"><img alt=" Fabien\'s Bar "/></a>
  915. <a href="/bar"><img alt="Fabien&quot;s Bar"/></a>
  916. <a href="/bar"><img alt="\' Fabien&quot;s Bar"/></a>
  917. <a href="?get=param">GetLink</a>
  918. <a href="/example">Klausi|Claudiu</a>
  919. <form action="foo" id="FooFormId">
  920. <input type="text" value="TextValue" name="TextName" />
  921. <input type="submit" value="FooValue" name="FooName" id="FooId" />
  922. <input type="button" value="BarValue" name="BarName" id="BarId" />
  923. <button value="ButtonValue" name="ButtonName" id="ButtonId" />
  924. </form>
  925. <input type="submit" value="FooBarValue" name="FooBarName" form="FooFormId" />
  926. <input type="text" value="FooTextValue" name="FooTextName" form="FooFormId" />
  927. <ul class="first">
  928. <li class="first">One</li>
  929. <li>Two</li>
  930. <li>Three</li>
  931. </ul>
  932. <ul>
  933. <li>One Bis</li>
  934. <li>Two Bis</li>
  935. <li>Three Bis</li>
  936. </ul>
  937. <div id="parent">
  938. <div id="child"></div>
  939. <div id="child2" xmlns:foo="http://example.com"></div>
  940. </div>
  941. <div id="sibling"><img /></div>
  942. </body>
  943. </html>
  944. ');
  945. return new Crawler($dom, $uri);
  946. }
  947. protected function createTestXmlCrawler($uri = null)
  948. {
  949. $xml = '<?xml version="1.0" encoding="UTF-8"?>
  950. <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
  951. <id>tag:youtube.com,2008:video:kgZRZmEc9j4</id>
  952. <yt:accessControl action="comment" permission="allowed"/>
  953. <yt:accessControl action="videoRespond" permission="moderated"/>
  954. <media:group>
  955. <media:title type="plain">Chordates - CrashCourse Biology #24</media:title>
  956. <yt:aspectRatio>widescreen</yt:aspectRatio>
  957. </media:group>
  958. <media:category label="Music" scheme="http://gdata.youtube.com/schemas/2007/categories.cat">Music</media:category>
  959. </entry>';
  960. return new Crawler($xml, $uri);
  961. }
  962. protected function createDomDocument()
  963. {
  964. $dom = new \DOMDocument();
  965. $dom->loadXML('<html><div class="foo"></div></html>');
  966. return $dom;
  967. }
  968. protected function createNodeList()
  969. {
  970. $dom = new \DOMDocument();
  971. $dom->loadXML('<html><div class="foo"></div></html>');
  972. $domxpath = new \DOMXPath($dom);
  973. return $domxpath->query('//div');
  974. }
  975. }