Crawler.php 39 KB

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