Crawler.php 40 KB

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