Crawler.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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;
  11. use Symfony\Component\CssSelector\CssSelectorConverter;
  12. /**
  13. * Crawler eases navigation of a list of \DOMNode objects.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class Crawler implements \Countable, \IteratorAggregate
  18. {
  19. protected $uri;
  20. /**
  21. * @var string The default namespace prefix to be used with XPath and CSS expressions
  22. */
  23. private $defaultNamespacePrefix = 'default';
  24. /**
  25. * @var array A map of manually registered namespaces
  26. */
  27. private $namespaces = [];
  28. /**
  29. * @var string The base href value
  30. */
  31. private $baseHref;
  32. /**
  33. * @var \DOMDocument|null
  34. */
  35. private $document;
  36. /**
  37. * @var \DOMElement[]
  38. */
  39. private $nodes = [];
  40. /**
  41. * Whether the Crawler contains HTML or XML content (used when converting CSS to XPath).
  42. *
  43. * @var bool
  44. */
  45. private $isHtml = true;
  46. /**
  47. * @param mixed $node A Node to use as the base for the crawling
  48. * @param string $uri The current URI
  49. * @param string $baseHref The base href value
  50. */
  51. public function __construct($node = null, string $uri = null, string $baseHref = null)
  52. {
  53. $this->uri = $uri;
  54. $this->baseHref = $baseHref ?: $uri;
  55. $this->add($node);
  56. }
  57. /**
  58. * Returns the current URI.
  59. *
  60. * @return string
  61. */
  62. public function getUri()
  63. {
  64. return $this->uri;
  65. }
  66. /**
  67. * Returns base href.
  68. *
  69. * @return string
  70. */
  71. public function getBaseHref()
  72. {
  73. return $this->baseHref;
  74. }
  75. /**
  76. * Removes all the nodes.
  77. */
  78. public function clear()
  79. {
  80. $this->nodes = [];
  81. $this->document = null;
  82. }
  83. /**
  84. * Adds a node to the current list of nodes.
  85. *
  86. * This method uses the appropriate specialized add*() method based
  87. * on the type of the argument.
  88. *
  89. * @param \DOMNodeList|\DOMNode|array|string|null $node A node
  90. *
  91. * @throws \InvalidArgumentException when node is not the expected type
  92. */
  93. public function add($node)
  94. {
  95. if ($node instanceof \DOMNodeList) {
  96. $this->addNodeList($node);
  97. } elseif ($node instanceof \DOMNode) {
  98. $this->addNode($node);
  99. } elseif (\is_array($node)) {
  100. $this->addNodes($node);
  101. } elseif (\is_string($node)) {
  102. $this->addContent($node);
  103. } elseif (null !== $node) {
  104. throw new \InvalidArgumentException(sprintf('Expecting a DOMNodeList or DOMNode instance, an array, a string, or null, but got "%s".', \is_object($node) ? \get_class($node) : \gettype($node)));
  105. }
  106. }
  107. /**
  108. * Adds HTML/XML content.
  109. *
  110. * If the charset is not set via the content type, it is assumed to be UTF-8,
  111. * or ISO-8859-1 as a fallback, which is the default charset defined by the
  112. * HTTP 1.1 specification.
  113. *
  114. * @param string $content A string to parse as HTML/XML
  115. * @param string|null $type The content type of the string
  116. */
  117. public function addContent($content, $type = null)
  118. {
  119. if (empty($type)) {
  120. $type = 0 === strpos($content, '<?xml') ? 'application/xml' : 'text/html';
  121. }
  122. // DOM only for HTML/XML content
  123. if (!preg_match('/(x|ht)ml/i', $type, $xmlMatches)) {
  124. return;
  125. }
  126. $charset = null;
  127. if (false !== $pos = stripos($type, 'charset=')) {
  128. $charset = substr($type, $pos + 8);
  129. if (false !== $pos = strpos($charset, ';')) {
  130. $charset = substr($charset, 0, $pos);
  131. }
  132. }
  133. // http://www.w3.org/TR/encoding/#encodings
  134. // http://www.w3.org/TR/REC-xml/#NT-EncName
  135. if (null === $charset &&
  136. preg_match('/\<meta[^\>]+charset *= *["\']?([a-zA-Z\-0-9_:.]+)/i', $content, $matches)) {
  137. $charset = $matches[1];
  138. }
  139. if (null === $charset) {
  140. $charset = preg_match('//u', $content) ? 'UTF-8' : 'ISO-8859-1';
  141. }
  142. if ('x' === $xmlMatches[1]) {
  143. $this->addXmlContent($content, $charset);
  144. } else {
  145. $this->addHtmlContent($content, $charset);
  146. }
  147. }
  148. /**
  149. * Adds an HTML content to the list of nodes.
  150. *
  151. * The libxml errors are disabled when the content is parsed.
  152. *
  153. * If you want to get parsing errors, be sure to enable
  154. * internal errors via libxml_use_internal_errors(true)
  155. * and then, get the errors via libxml_get_errors(). Be
  156. * sure to clear errors with libxml_clear_errors() afterward.
  157. *
  158. * @param string $content The HTML content
  159. * @param string $charset The charset
  160. */
  161. public function addHtmlContent($content, $charset = 'UTF-8')
  162. {
  163. $internalErrors = libxml_use_internal_errors(true);
  164. $disableEntities = libxml_disable_entity_loader(true);
  165. $dom = new \DOMDocument('1.0', $charset);
  166. $dom->validateOnParse = true;
  167. set_error_handler(function () { throw new \Exception(); });
  168. try {
  169. // Convert charset to HTML-entities to work around bugs in DOMDocument::loadHTML()
  170. $content = mb_convert_encoding($content, 'HTML-ENTITIES', $charset);
  171. } catch (\Exception $e) {
  172. }
  173. restore_error_handler();
  174. if ('' !== trim($content)) {
  175. @$dom->loadHTML($content);
  176. }
  177. libxml_use_internal_errors($internalErrors);
  178. libxml_disable_entity_loader($disableEntities);
  179. $this->addDocument($dom);
  180. $base = $this->filterRelativeXPath('descendant-or-self::base')->extract(['href']);
  181. $baseHref = current($base);
  182. if (\count($base) && !empty($baseHref)) {
  183. if ($this->baseHref) {
  184. $linkNode = $dom->createElement('a');
  185. $linkNode->setAttribute('href', $baseHref);
  186. $link = new Link($linkNode, $this->baseHref);
  187. $this->baseHref = $link->getUri();
  188. } else {
  189. $this->baseHref = $baseHref;
  190. }
  191. }
  192. }
  193. /**
  194. * Adds an XML content to the list of nodes.
  195. *
  196. * The libxml errors are disabled when the content is parsed.
  197. *
  198. * If you want to get parsing errors, be sure to enable
  199. * internal errors via libxml_use_internal_errors(true)
  200. * and then, get the errors via libxml_get_errors(). Be
  201. * sure to clear errors with libxml_clear_errors() afterward.
  202. *
  203. * @param string $content The XML content
  204. * @param string $charset The charset
  205. * @param int $options Bitwise OR of the libxml option constants
  206. * LIBXML_PARSEHUGE is dangerous, see
  207. * http://symfony.com/blog/security-release-symfony-2-0-17-released
  208. */
  209. public function addXmlContent($content, $charset = 'UTF-8', $options = LIBXML_NONET)
  210. {
  211. // remove the default namespace if it's the only namespace to make XPath expressions simpler
  212. if (!preg_match('/xmlns:/', $content)) {
  213. $content = str_replace('xmlns', 'ns', $content);
  214. }
  215. $internalErrors = libxml_use_internal_errors(true);
  216. $disableEntities = libxml_disable_entity_loader(true);
  217. $dom = new \DOMDocument('1.0', $charset);
  218. $dom->validateOnParse = true;
  219. if ('' !== trim($content)) {
  220. @$dom->loadXML($content, $options);
  221. }
  222. libxml_use_internal_errors($internalErrors);
  223. libxml_disable_entity_loader($disableEntities);
  224. $this->addDocument($dom);
  225. $this->isHtml = false;
  226. }
  227. /**
  228. * Adds a \DOMDocument to the list of nodes.
  229. *
  230. * @param \DOMDocument $dom A \DOMDocument instance
  231. */
  232. public function addDocument(\DOMDocument $dom)
  233. {
  234. if ($dom->documentElement) {
  235. $this->addNode($dom->documentElement);
  236. }
  237. }
  238. /**
  239. * Adds a \DOMNodeList to the list of nodes.
  240. *
  241. * @param \DOMNodeList $nodes A \DOMNodeList instance
  242. */
  243. public function addNodeList(\DOMNodeList $nodes)
  244. {
  245. foreach ($nodes as $node) {
  246. if ($node instanceof \DOMNode) {
  247. $this->addNode($node);
  248. }
  249. }
  250. }
  251. /**
  252. * Adds an array of \DOMNode instances to the list of nodes.
  253. *
  254. * @param \DOMNode[] $nodes An array of \DOMNode instances
  255. */
  256. public function addNodes(array $nodes)
  257. {
  258. foreach ($nodes as $node) {
  259. $this->add($node);
  260. }
  261. }
  262. /**
  263. * Adds a \DOMNode instance to the list of nodes.
  264. *
  265. * @param \DOMNode $node A \DOMNode instance
  266. */
  267. public function addNode(\DOMNode $node)
  268. {
  269. if ($node instanceof \DOMDocument) {
  270. $node = $node->documentElement;
  271. }
  272. if (null !== $this->document && $this->document !== $node->ownerDocument) {
  273. throw new \InvalidArgumentException('Attaching DOM nodes from multiple documents in the same crawler is forbidden.');
  274. }
  275. if (null === $this->document) {
  276. $this->document = $node->ownerDocument;
  277. }
  278. // Don't add duplicate nodes in the Crawler
  279. if (\in_array($node, $this->nodes, true)) {
  280. return;
  281. }
  282. $this->nodes[] = $node;
  283. }
  284. /**
  285. * Returns a node given its position in the node list.
  286. *
  287. * @param int $position The position
  288. *
  289. * @return self
  290. */
  291. public function eq($position)
  292. {
  293. if (isset($this->nodes[$position])) {
  294. return $this->createSubCrawler($this->nodes[$position]);
  295. }
  296. return $this->createSubCrawler(null);
  297. }
  298. /**
  299. * Calls an anonymous function on each node of the list.
  300. *
  301. * The anonymous function receives the position and the node wrapped
  302. * in a Crawler instance as arguments.
  303. *
  304. * Example:
  305. *
  306. * $crawler->filter('h1')->each(function ($node, $i) {
  307. * return $node->text();
  308. * });
  309. *
  310. * @param \Closure $closure An anonymous function
  311. *
  312. * @return array An array of values returned by the anonymous function
  313. */
  314. public function each(\Closure $closure)
  315. {
  316. $data = [];
  317. foreach ($this->nodes as $i => $node) {
  318. $data[] = $closure($this->createSubCrawler($node), $i);
  319. }
  320. return $data;
  321. }
  322. /**
  323. * Slices the list of nodes by $offset and $length.
  324. *
  325. * @param int $offset
  326. * @param int $length
  327. *
  328. * @return self
  329. */
  330. public function slice($offset = 0, $length = null)
  331. {
  332. return $this->createSubCrawler(\array_slice($this->nodes, $offset, $length));
  333. }
  334. /**
  335. * Reduces the list of nodes by calling an anonymous function.
  336. *
  337. * To remove a node from the list, the anonymous function must return false.
  338. *
  339. * @param \Closure $closure An anonymous function
  340. *
  341. * @return self
  342. */
  343. public function reduce(\Closure $closure)
  344. {
  345. $nodes = [];
  346. foreach ($this->nodes as $i => $node) {
  347. if (false !== $closure($this->createSubCrawler($node), $i)) {
  348. $nodes[] = $node;
  349. }
  350. }
  351. return $this->createSubCrawler($nodes);
  352. }
  353. /**
  354. * Returns the first node of the current selection.
  355. *
  356. * @return self
  357. */
  358. public function first()
  359. {
  360. return $this->eq(0);
  361. }
  362. /**
  363. * Returns the last node of the current selection.
  364. *
  365. * @return self
  366. */
  367. public function last()
  368. {
  369. return $this->eq(\count($this->nodes) - 1);
  370. }
  371. /**
  372. * Returns the siblings nodes of the current selection.
  373. *
  374. * @return self
  375. *
  376. * @throws \InvalidArgumentException When current node is empty
  377. */
  378. public function siblings()
  379. {
  380. if (!$this->nodes) {
  381. throw new \InvalidArgumentException('The current node list is empty.');
  382. }
  383. return $this->createSubCrawler($this->sibling($this->getNode(0)->parentNode->firstChild));
  384. }
  385. /**
  386. * Returns the next siblings nodes of the current selection.
  387. *
  388. * @return self
  389. *
  390. * @throws \InvalidArgumentException When current node is empty
  391. */
  392. public function nextAll()
  393. {
  394. if (!$this->nodes) {
  395. throw new \InvalidArgumentException('The current node list is empty.');
  396. }
  397. return $this->createSubCrawler($this->sibling($this->getNode(0)));
  398. }
  399. /**
  400. * Returns the previous sibling nodes of the current selection.
  401. *
  402. * @return self
  403. *
  404. * @throws \InvalidArgumentException
  405. */
  406. public function previousAll()
  407. {
  408. if (!$this->nodes) {
  409. throw new \InvalidArgumentException('The current node list is empty.');
  410. }
  411. return $this->createSubCrawler($this->sibling($this->getNode(0), 'previousSibling'));
  412. }
  413. /**
  414. * Returns the parents nodes of the current selection.
  415. *
  416. * @return self
  417. *
  418. * @throws \InvalidArgumentException When current node is empty
  419. */
  420. public function parents()
  421. {
  422. if (!$this->nodes) {
  423. throw new \InvalidArgumentException('The current node list is empty.');
  424. }
  425. $node = $this->getNode(0);
  426. $nodes = [];
  427. while ($node = $node->parentNode) {
  428. if (XML_ELEMENT_NODE === $node->nodeType) {
  429. $nodes[] = $node;
  430. }
  431. }
  432. return $this->createSubCrawler($nodes);
  433. }
  434. /**
  435. * Returns the children nodes of the current selection.
  436. *
  437. * @param string|null $selector An optional CSS selector to filter children
  438. *
  439. * @return self
  440. *
  441. * @throws \InvalidArgumentException When current node is empty
  442. * @throws \RuntimeException If the CssSelector Component is not available and $selector is provided
  443. */
  444. public function children(/* string $selector = null */)
  445. {
  446. if (\func_num_args() < 1 && __CLASS__ !== \get_class($this) && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) {
  447. @trigger_error(sprintf('The "%s()" method will have a new "string $selector = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED);
  448. }
  449. $selector = 0 < \func_num_args() ? func_get_arg(0) : null;
  450. if (!$this->nodes) {
  451. throw new \InvalidArgumentException('The current node list is empty.');
  452. }
  453. if (null !== $selector) {
  454. $converter = $this->createCssSelectorConverter();
  455. $xpath = $converter->toXPath($selector, 'child::');
  456. return $this->filterRelativeXPath($xpath);
  457. }
  458. $node = $this->getNode(0)->firstChild;
  459. return $this->createSubCrawler($node ? $this->sibling($node) : []);
  460. }
  461. /**
  462. * Returns the attribute value of the first node of the list.
  463. *
  464. * @param string $attribute The attribute name
  465. *
  466. * @return string|null The attribute value or null if the attribute does not exist
  467. *
  468. * @throws \InvalidArgumentException When current node is empty
  469. */
  470. public function attr($attribute)
  471. {
  472. if (!$this->nodes) {
  473. throw new \InvalidArgumentException('The current node list is empty.');
  474. }
  475. $node = $this->getNode(0);
  476. return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : null;
  477. }
  478. /**
  479. * Returns the node name of the first node of the list.
  480. *
  481. * @return string The node name
  482. *
  483. * @throws \InvalidArgumentException When current node is empty
  484. */
  485. public function nodeName()
  486. {
  487. if (!$this->nodes) {
  488. throw new \InvalidArgumentException('The current node list is empty.');
  489. }
  490. return $this->getNode(0)->nodeName;
  491. }
  492. /**
  493. * Returns the node value of the first node of the list.
  494. *
  495. * @param mixed $default When provided and the current node is empty, this value is returned and no exception is thrown
  496. *
  497. * @return string The node value
  498. *
  499. * @throws \InvalidArgumentException When current node is empty
  500. */
  501. public function text(/* $default = null */)
  502. {
  503. if (!$this->nodes) {
  504. if (0 < \func_num_args()) {
  505. return \func_get_arg(0);
  506. }
  507. throw new \InvalidArgumentException('The current node list is empty.');
  508. }
  509. return $this->getNode(0)->nodeValue;
  510. }
  511. /**
  512. * Returns the first node of the list as HTML.
  513. *
  514. * @param mixed $default When provided and the current node is empty, this value is returned and no exception is thrown
  515. *
  516. * @return string The node html
  517. *
  518. * @throws \InvalidArgumentException When current node is empty
  519. */
  520. public function html(/* $default = null */)
  521. {
  522. if (!$this->nodes) {
  523. if (0 < \func_num_args()) {
  524. return \func_get_arg(0);
  525. }
  526. throw new \InvalidArgumentException('The current node list is empty.');
  527. }
  528. $html = '';
  529. foreach ($this->getNode(0)->childNodes as $child) {
  530. $html .= $child->ownerDocument->saveHTML($child);
  531. }
  532. return $html;
  533. }
  534. /**
  535. * Evaluates an XPath expression.
  536. *
  537. * Since an XPath expression might evaluate to either a simple type or a \DOMNodeList,
  538. * this method will return either an array of simple types or a new Crawler instance.
  539. *
  540. * @param string $xpath An XPath expression
  541. *
  542. * @return array|Crawler An array of evaluation results or a new Crawler instance
  543. */
  544. public function evaluate($xpath)
  545. {
  546. if (null === $this->document) {
  547. throw new \LogicException('Cannot evaluate the expression on an uninitialized crawler.');
  548. }
  549. $data = [];
  550. $domxpath = $this->createDOMXPath($this->document, $this->findNamespacePrefixes($xpath));
  551. foreach ($this->nodes as $node) {
  552. $data[] = $domxpath->evaluate($xpath, $node);
  553. }
  554. if (isset($data[0]) && $data[0] instanceof \DOMNodeList) {
  555. return $this->createSubCrawler($data);
  556. }
  557. return $data;
  558. }
  559. /**
  560. * Extracts information from the list of nodes.
  561. *
  562. * You can extract attributes or/and the node value (_text).
  563. *
  564. * Example:
  565. *
  566. * $crawler->filter('h1 a')->extract(['_text', 'href']);
  567. *
  568. * @param array $attributes An array of attributes
  569. *
  570. * @return array An array of extracted values
  571. */
  572. public function extract($attributes)
  573. {
  574. $attributes = (array) $attributes;
  575. $count = \count($attributes);
  576. $data = [];
  577. foreach ($this->nodes as $node) {
  578. $elements = [];
  579. foreach ($attributes as $attribute) {
  580. if ('_text' === $attribute) {
  581. $elements[] = $node->nodeValue;
  582. } elseif ('_name' === $attribute) {
  583. $elements[] = $node->nodeName;
  584. } else {
  585. $elements[] = $node->getAttribute($attribute);
  586. }
  587. }
  588. $data[] = 1 === $count ? $elements[0] : $elements;
  589. }
  590. return $data;
  591. }
  592. /**
  593. * Filters the list of nodes with an XPath expression.
  594. *
  595. * The XPath expression is evaluated in the context of the crawler, which
  596. * is considered as a fake parent of the elements inside it.
  597. * This means that a child selector "div" or "./div" will match only
  598. * the div elements of the current crawler, not their children.
  599. *
  600. * @param string $xpath An XPath expression
  601. *
  602. * @return self
  603. */
  604. public function filterXPath($xpath)
  605. {
  606. $xpath = $this->relativize($xpath);
  607. // If we dropped all expressions in the XPath while preparing it, there would be no match
  608. if ('' === $xpath) {
  609. return $this->createSubCrawler(null);
  610. }
  611. return $this->filterRelativeXPath($xpath);
  612. }
  613. /**
  614. * Filters the list of nodes with a CSS selector.
  615. *
  616. * This method only works if you have installed the CssSelector Symfony Component.
  617. *
  618. * @param string $selector A CSS selector
  619. *
  620. * @return self
  621. *
  622. * @throws \RuntimeException if the CssSelector Component is not available
  623. */
  624. public function filter($selector)
  625. {
  626. $converter = $this->createCssSelectorConverter();
  627. // The CssSelector already prefixes the selector with descendant-or-self::
  628. return $this->filterRelativeXPath($converter->toXPath($selector));
  629. }
  630. /**
  631. * Selects links by name or alt value for clickable images.
  632. *
  633. * @param string $value The link text
  634. *
  635. * @return self
  636. */
  637. public function selectLink($value)
  638. {
  639. return $this->filterRelativeXPath(
  640. sprintf('descendant-or-self::a[contains(concat(\' \', normalize-space(string(.)), \' \'), %1$s) or ./img[contains(concat(\' \', normalize-space(string(@alt)), \' \'), %1$s)]]', static::xpathLiteral(' '.$value.' '))
  641. );
  642. }
  643. /**
  644. * Selects images by alt value.
  645. *
  646. * @param string $value The image alt
  647. *
  648. * @return self A new instance of Crawler with the filtered list of nodes
  649. */
  650. public function selectImage($value)
  651. {
  652. $xpath = sprintf('descendant-or-self::img[contains(normalize-space(string(@alt)), %s)]', static::xpathLiteral($value));
  653. return $this->filterRelativeXPath($xpath);
  654. }
  655. /**
  656. * Selects a button by name or alt value for images.
  657. *
  658. * @param string $value The button text
  659. *
  660. * @return self
  661. */
  662. public function selectButton($value)
  663. {
  664. return $this->filterRelativeXPath(
  665. sprintf('descendant-or-self::input[((contains(%1$s, "submit") or contains(%1$s, "button")) and contains(concat(\' \', normalize-space(string(@value)), \' \'), %2$s)) or (contains(%1$s, "image") and contains(concat(\' \', normalize-space(string(@alt)), \' \'), %2$s)) or @id=%3$s or @name=%3$s] | descendant-or-self::button[contains(concat(\' \', normalize-space(string(.)), \' \'), %2$s) or @id=%3$s or @name=%3$s]', 'translate(@type, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")', static::xpathLiteral(' '.$value.' '), static::xpathLiteral($value))
  666. );
  667. }
  668. /**
  669. * Returns a Link object for the first node in the list.
  670. *
  671. * @param string $method The method for the link (get by default)
  672. *
  673. * @return Link A Link instance
  674. *
  675. * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
  676. */
  677. public function link($method = 'get')
  678. {
  679. if (!$this->nodes) {
  680. throw new \InvalidArgumentException('The current node list is empty.');
  681. }
  682. $node = $this->getNode(0);
  683. if (!$node instanceof \DOMElement) {
  684. throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
  685. }
  686. return new Link($node, $this->baseHref, $method);
  687. }
  688. /**
  689. * Returns an array of Link objects for the nodes in the list.
  690. *
  691. * @return Link[] An array of Link instances
  692. *
  693. * @throws \InvalidArgumentException If the current node list contains non-DOMElement instances
  694. */
  695. public function links()
  696. {
  697. $links = [];
  698. foreach ($this->nodes as $node) {
  699. if (!$node instanceof \DOMElement) {
  700. throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', \get_class($node)));
  701. }
  702. $links[] = new Link($node, $this->baseHref, 'get');
  703. }
  704. return $links;
  705. }
  706. /**
  707. * Returns an Image object for the first node in the list.
  708. *
  709. * @return Image An Image instance
  710. *
  711. * @throws \InvalidArgumentException If the current node list is empty
  712. */
  713. public function image()
  714. {
  715. if (!\count($this)) {
  716. throw new \InvalidArgumentException('The current node list is empty.');
  717. }
  718. $node = $this->getNode(0);
  719. if (!$node instanceof \DOMElement) {
  720. throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
  721. }
  722. return new Image($node, $this->baseHref);
  723. }
  724. /**
  725. * Returns an array of Image objects for the nodes in the list.
  726. *
  727. * @return Image[] An array of Image instances
  728. */
  729. public function images()
  730. {
  731. $images = [];
  732. foreach ($this as $node) {
  733. if (!$node instanceof \DOMElement) {
  734. throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', \get_class($node)));
  735. }
  736. $images[] = new Image($node, $this->baseHref);
  737. }
  738. return $images;
  739. }
  740. /**
  741. * Returns a Form object for the first node in the list.
  742. *
  743. * @param array $values An array of values for the form fields
  744. * @param string $method The method for the form
  745. *
  746. * @return Form A Form instance
  747. *
  748. * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
  749. */
  750. public function form(array $values = null, $method = null)
  751. {
  752. if (!$this->nodes) {
  753. throw new \InvalidArgumentException('The current node list is empty.');
  754. }
  755. $node = $this->getNode(0);
  756. if (!$node instanceof \DOMElement) {
  757. throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
  758. }
  759. $form = new Form($node, $this->uri, $method, $this->baseHref);
  760. if (null !== $values) {
  761. $form->setValues($values);
  762. }
  763. return $form;
  764. }
  765. /**
  766. * Overloads a default namespace prefix to be used with XPath and CSS expressions.
  767. *
  768. * @param string $prefix
  769. */
  770. public function setDefaultNamespacePrefix($prefix)
  771. {
  772. $this->defaultNamespacePrefix = $prefix;
  773. }
  774. /**
  775. * @param string $prefix
  776. * @param string $namespace
  777. */
  778. public function registerNamespace($prefix, $namespace)
  779. {
  780. $this->namespaces[$prefix] = $namespace;
  781. }
  782. /**
  783. * Converts string for XPath expressions.
  784. *
  785. * Escaped characters are: quotes (") and apostrophe (').
  786. *
  787. * Examples:
  788. *
  789. * echo Crawler::xpathLiteral('foo " bar');
  790. * //prints 'foo " bar'
  791. *
  792. * echo Crawler::xpathLiteral("foo ' bar");
  793. * //prints "foo ' bar"
  794. *
  795. * echo Crawler::xpathLiteral('a\'b"c');
  796. * //prints concat('a', "'", 'b"c')
  797. *
  798. *
  799. * @param string $s String to be escaped
  800. *
  801. * @return string Converted string
  802. */
  803. public static function xpathLiteral($s)
  804. {
  805. if (false === strpos($s, "'")) {
  806. return sprintf("'%s'", $s);
  807. }
  808. if (false === strpos($s, '"')) {
  809. return sprintf('"%s"', $s);
  810. }
  811. $string = $s;
  812. $parts = [];
  813. while (true) {
  814. if (false !== $pos = strpos($string, "'")) {
  815. $parts[] = sprintf("'%s'", substr($string, 0, $pos));
  816. $parts[] = "\"'\"";
  817. $string = substr($string, $pos + 1);
  818. } else {
  819. $parts[] = "'$string'";
  820. break;
  821. }
  822. }
  823. return sprintf('concat(%s)', implode(', ', $parts));
  824. }
  825. /**
  826. * Filters the list of nodes with an XPath expression.
  827. *
  828. * The XPath expression should already be processed to apply it in the context of each node.
  829. *
  830. * @param string $xpath
  831. *
  832. * @return self
  833. */
  834. private function filterRelativeXPath($xpath)
  835. {
  836. $prefixes = $this->findNamespacePrefixes($xpath);
  837. $crawler = $this->createSubCrawler(null);
  838. foreach ($this->nodes as $node) {
  839. $domxpath = $this->createDOMXPath($node->ownerDocument, $prefixes);
  840. $crawler->add($domxpath->query($xpath, $node));
  841. }
  842. return $crawler;
  843. }
  844. /**
  845. * Make the XPath relative to the current context.
  846. *
  847. * The returned XPath will match elements matching the XPath inside the current crawler
  848. * when running in the context of a node of the crawler.
  849. */
  850. private function relativize(string $xpath): string
  851. {
  852. $expressions = [];
  853. // An expression which will never match to replace expressions which cannot match in the crawler
  854. // We cannot simply drop
  855. $nonMatchingExpression = 'a[name() = "b"]';
  856. $xpathLen = \strlen($xpath);
  857. $openedBrackets = 0;
  858. $startPosition = strspn($xpath, " \t\n\r\0\x0B");
  859. for ($i = $startPosition; $i <= $xpathLen; ++$i) {
  860. $i += strcspn($xpath, '"\'[]|', $i);
  861. if ($i < $xpathLen) {
  862. switch ($xpath[$i]) {
  863. case '"':
  864. case "'":
  865. if (false === $i = strpos($xpath, $xpath[$i], $i + 1)) {
  866. return $xpath; // The XPath expression is invalid
  867. }
  868. continue 2;
  869. case '[':
  870. ++$openedBrackets;
  871. continue 2;
  872. case ']':
  873. --$openedBrackets;
  874. continue 2;
  875. }
  876. }
  877. if ($openedBrackets) {
  878. continue;
  879. }
  880. if ($startPosition < $xpathLen && '(' === $xpath[$startPosition]) {
  881. // If the union is inside some braces, we need to preserve the opening braces and apply
  882. // the change only inside it.
  883. $j = 1 + strspn($xpath, "( \t\n\r\0\x0B", $startPosition + 1);
  884. $parenthesis = substr($xpath, $startPosition, $j);
  885. $startPosition += $j;
  886. } else {
  887. $parenthesis = '';
  888. }
  889. $expression = rtrim(substr($xpath, $startPosition, $i - $startPosition));
  890. if (0 === strpos($expression, 'self::*/')) {
  891. $expression = './'.substr($expression, 8);
  892. }
  893. // add prefix before absolute element selector
  894. if ('' === $expression) {
  895. $expression = $nonMatchingExpression;
  896. } elseif (0 === strpos($expression, '//')) {
  897. $expression = 'descendant-or-self::'.substr($expression, 2);
  898. } elseif (0 === strpos($expression, './/')) {
  899. $expression = 'descendant-or-self::'.substr($expression, 3);
  900. } elseif (0 === strpos($expression, './')) {
  901. $expression = 'self::'.substr($expression, 2);
  902. } elseif (0 === strpos($expression, 'child::')) {
  903. $expression = 'self::'.substr($expression, 7);
  904. } elseif ('/' === $expression[0] || '.' === $expression[0] || 0 === strpos($expression, 'self::')) {
  905. $expression = $nonMatchingExpression;
  906. } elseif (0 === strpos($expression, 'descendant::')) {
  907. $expression = 'descendant-or-self::'.substr($expression, 12);
  908. } elseif (preg_match('/^(ancestor|ancestor-or-self|attribute|following|following-sibling|namespace|parent|preceding|preceding-sibling)::/', $expression)) {
  909. // the fake root has no parent, preceding or following nodes and also no attributes (even no namespace attributes)
  910. $expression = $nonMatchingExpression;
  911. } elseif (0 !== strpos($expression, 'descendant-or-self::')) {
  912. $expression = 'self::'.$expression;
  913. }
  914. $expressions[] = $parenthesis.$expression;
  915. if ($i === $xpathLen) {
  916. return implode(' | ', $expressions);
  917. }
  918. $i += strspn($xpath, " \t\n\r\0\x0B", $i + 1);
  919. $startPosition = $i + 1;
  920. }
  921. return $xpath; // The XPath expression is invalid
  922. }
  923. /**
  924. * @param int $position
  925. *
  926. * @return \DOMElement|null
  927. */
  928. public function getNode($position)
  929. {
  930. if (isset($this->nodes[$position])) {
  931. return $this->nodes[$position];
  932. }
  933. }
  934. /**
  935. * @return int
  936. */
  937. public function count()
  938. {
  939. return \count($this->nodes);
  940. }
  941. /**
  942. * @return \ArrayIterator|\DOMElement[]
  943. */
  944. public function getIterator()
  945. {
  946. return new \ArrayIterator($this->nodes);
  947. }
  948. /**
  949. * @param \DOMElement $node
  950. * @param string $siblingDir
  951. *
  952. * @return array
  953. */
  954. protected function sibling($node, $siblingDir = 'nextSibling')
  955. {
  956. $nodes = [];
  957. $currentNode = $this->getNode(0);
  958. do {
  959. if ($node !== $currentNode && XML_ELEMENT_NODE === $node->nodeType) {
  960. $nodes[] = $node;
  961. }
  962. } while ($node = $node->$siblingDir);
  963. return $nodes;
  964. }
  965. /**
  966. * @throws \InvalidArgumentException
  967. */
  968. private function createDOMXPath(\DOMDocument $document, array $prefixes = []): \DOMXPath
  969. {
  970. $domxpath = new \DOMXPath($document);
  971. foreach ($prefixes as $prefix) {
  972. $namespace = $this->discoverNamespace($domxpath, $prefix);
  973. if (null !== $namespace) {
  974. $domxpath->registerNamespace($prefix, $namespace);
  975. }
  976. }
  977. return $domxpath;
  978. }
  979. /**
  980. * @throws \InvalidArgumentException
  981. */
  982. private function discoverNamespace(\DOMXPath $domxpath, string $prefix): ?string
  983. {
  984. if (isset($this->namespaces[$prefix])) {
  985. return $this->namespaces[$prefix];
  986. }
  987. // ask for one namespace, otherwise we'd get a collection with an item for each node
  988. $namespaces = $domxpath->query(sprintf('(//namespace::*[name()="%s"])[last()]', $this->defaultNamespacePrefix === $prefix ? '' : $prefix));
  989. if ($node = $namespaces->item(0)) {
  990. return $node->nodeValue;
  991. }
  992. return null;
  993. }
  994. private function findNamespacePrefixes(string $xpath): array
  995. {
  996. if (preg_match_all('/(?P<prefix>[a-z_][a-z_0-9\-\.]*+):[^"\/:]/i', $xpath, $matches)) {
  997. return array_unique($matches['prefix']);
  998. }
  999. return [];
  1000. }
  1001. /**
  1002. * Creates a crawler for some subnodes.
  1003. *
  1004. * @param \DOMElement|\DOMElement[]|\DOMNodeList|null $nodes
  1005. *
  1006. * @return static
  1007. */
  1008. private function createSubCrawler($nodes)
  1009. {
  1010. $crawler = new static($nodes, $this->uri, $this->baseHref);
  1011. $crawler->isHtml = $this->isHtml;
  1012. $crawler->document = $this->document;
  1013. $crawler->namespaces = $this->namespaces;
  1014. return $crawler;
  1015. }
  1016. /**
  1017. * @throws \RuntimeException If the CssSelector Component is not available
  1018. */
  1019. private function createCssSelectorConverter(): CssSelectorConverter
  1020. {
  1021. if (!\class_exists(CssSelectorConverter::class)) {
  1022. throw new \LogicException('To filter with a CSS selector, install the CssSelector component ("composer require symfony/css-selector"). Or use filterXpath instead.');
  1023. }
  1024. return new CssSelectorConverter($this->isHtml);
  1025. }
  1026. }