Crawler.php 40 KB

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