Crawler.php 37 KB

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