Parse the HTML form.
@param  string $html
@param  string $xpath xpath to form
554098
public static function parse($html, $xpath) {
		$doc = new \DOMDocument();
		$doc->loadHTML($html);
		$domxpath = new \DOMXPath($doc);
		$node = $domxpath->evaluate($xpath)->item(0);

		return new static($node);
	}
369801
public function parse(string $html): string
    {
        $html = ltrim($html);
        $this->setTokenPosition($html);

        try {
            $this->name = $this->parseElementName($html);
            $remainingHtml = $this->parseAttributes($html);
            $posOfClosingBracket = $this->getPositionOfElementEndTag($remainingHtml);

            // Is self-closing?
            $posOfSelfClosingBracket = \mb_strpos($remainingHtml, '/>');
            $remainingHtml = \mb_substr($remainingHtml, $posOfClosingBracket + 1);
            if ($posOfSelfClosingBracket !== false && $posOfSelfClosingBracket === $posOfClosingBracket - 1) {
                // Self-closing element. (Note: $this->valuue is unchanged.)
                return $remainingHtml;
            }

            // Lets close those closed-only elements that are left open.
            if (\in_array($this->name, self::VOID_ELEMENTS, true)) {
                return $remainingHtml;
            }

            // Open element.
            return $this->parseContents($remainingHtml);
        } catch (ParseException $e) {
            if ($this->getThrowOnError()) {
                throw $e;
            }
        }

        return '';
    }
675150
public function iFollowXpath($xpath)
    {
        $result = $this->getSession()->getPage()->find('xpath', $xpath);

        if (is_null($result)) {
            // We did not find the link or we've found more than we want
            throw new ExpectationException(
                sprintf(
                    'The xpath %s (on %s) returned no elements',
                    $xpath,
                    $this->getSession()->getCurrentUrl()
                ),
                $this->getSession()->getDriver()
            );
        }

        $result->click();
    }
8149
public function loadHtml($html)
    {
        if (!is_string($html)) {
            throw new InvalidArgumentException(__METHOD__ . ' expects parameter 1 to be string.');
        }

        libxml_use_internal_errors(true);
        libxml_disable_entity_loader(true);

        $sxe = simplexml_load_string($html);
        if (libxml_get_errors()) {
            $this->document->loadHTML('<?xml encoding="UTF-8">' . $html);
        } else {
            $this->document = dom_import_simplexml($sxe)->ownerDocument;
        }

        libxml_clear_errors();
        libxml_disable_entity_loader(false);
        libxml_use_internal_errors(false);

        return $this;
    }
654363
public function parse($html)
    {
        $this->logger->info('*** Starting parse process...');

        $this->dom = $this->loadHTML($html);

        // Checking for minimum HTML to work with.
        if (!($root = $this->dom->getElementsByTagName('body')->item(0)) || !$root->firstChild) {
            $this->logger->emergency('No body tag present or body tag empty');

            throw new ParseException('Invalid or incomplete HTML.');
        }

        $this->getMetadata();

        $this->getMainImage();

        while (true) {
            $root = $root->firstChild;

            $elementsToScore = $this->getNodes($root);
            $this->logger->debug(sprintf('Elements to score: \'%s\'', count($elementsToScore)));

            $result = $this->rateNodes($elementsToScore);

            /*
             * Now that we've gone through the full algorithm, check to see if
             * we got any meaningful content. If we didn't, we may need to re-run
             * grabArticle with different flags set. This gives us a higher likelihood of
             * finding the content, and the sieve approach gives us a higher likelihood of
             * finding the -right- content.
             */

            $length = mb_strlen(preg_replace(NodeUtility::$regexps['onlyWhitespace'], '', $result->textContent));

            $this->logger->info(sprintf('[Parsing] Article parsed. Amount of words: %s. Current threshold is: %s', $length, $this->configuration->getCharThreshold()));

            if ($result && $length < $this->configuration->getCharThreshold()) {
                $this->dom = $this->loadHTML($html);
                $root = $this->dom->getElementsByTagName('body')->item(0);

                if ($this->configuration->getStripUnlikelyCandidates()) {
                    $this->logger->debug('[Parsing] Threshold not met, trying again setting StripUnlikelyCandidates as false');
                    $this->configuration->setStripUnlikelyCandidates(false);
                    $this->attempts[] = ['articleContent' => $result, 'textLength' => $length];
                } elseif ($this->configuration->getWeightClasses()) {
                    $this->logger->debug('[Parsing] Threshold not met, trying again setting WeightClasses as false');
                    $this->configuration->setWeightClasses(false);
                    $this->attempts[] = ['articleContent' => $result, 'textLength' => $length];
                } elseif ($this->configuration->getCleanConditionally()) {
                    $this->logger->debug('[Parsing] Threshold not met, trying again setting CleanConditionally as false');
                    $this->configuration->setCleanConditionally(false);
                    $this->attempts[] = ['articleContent' => $result, 'textLength' => $length];
                } else {
                    $this->logger->debug('[Parsing] Threshold not met, searching across attempts for some content.');
                    $this->attempts[] = ['articleContent' => $result, 'textLength' => $length];

                    // No luck after removing flags, just return the longest text we found during the different loops
                    usort($this->attempts, function ($a, $b) {
                        return $a['textLength'] < $b['textLength'];
                    });

                    // But first check if we actually have something
                    if (!$this->attempts[0]['textLength']) {
                        $this->logger->emergency('[Parsing] Could not parse text, giving up :(');

                        throw new ParseException('Could not parse text.');
                    }

                    $this->logger->debug('[Parsing] Threshold not met, but found some content in previous attempts.');

                    $result = $this->attempts[0]['articleContent'];
                    break;
                }
            } else {
                break;
            }
        }

        $result = $this->postProcessContent($result);

        // If we haven't found an excerpt in the article's metadata, use the article's
        // first paragraph as the excerpt. This can be used for displaying a preview of
        // the article's content.
        if (!$this->getExcerpt()) {
            $this->logger->debug('[Parsing] No excerpt text found on metadata, extracting first p node and using it as excerpt.');
            $paragraphs = $result->getElementsByTagName('p');
            if ($paragraphs->length > 0) {
                $this->setExcerpt(trim($paragraphs->item(0)->textContent));
            }
        }

        $this->setContent($result);

        $this->logger->info('*** Parse successful :)');

        return true;
    }
760755
private function mapAllInlineStylesToHtmlAttributes(\DOMXPath $xPath)
    {
        /** @var \DOMElement $node */
        foreach ($this->getAllNodesWithStyleAttribute($xPath) as $node) {
            $inlineStyleDeclarations = $this->parseCssDeclarationsBlock($node->getAttribute('style'));
            $this->mapCssToHtmlAttributes($inlineStyleDeclarations, $node);
        }
    }
81557
protected function parseHtml()
    {
        $parser = new Parser($this->htmlStringOrFile);
        $document = $parser->setTableClass($this->tableClass)
            ->setRowClass($this->rowClass)
            ->setCellClass($this->cellClass)
            ->parse();

        $this->document = $document;

        return $document;
    }
754073
public function click($xpath) {
    $elements = $this->findElement($xpath, 1);
    $this->browser->click($elements["page_id"], $elements["ids"][0]);
  }
329394
protected function getFormField($xpath)
    {
        $fieldNode = $this->getCrawlerNode($this->getFilteredCrawler($xpath));
        $fieldName = str_replace('[]', '', $fieldNode->getAttribute('name'));

        $formNode = $this->getFormNode($fieldNode);
        $formId = $this->getFormNodeId($formNode);

        if (!isset($this->forms[$formId])) {
            $this->forms[$formId] = new Form($formNode, $this->getCurrentUrl());
        }

        if (is_array($this->forms[$formId][$fieldName])) {
            return $this->forms[$formId][$fieldName][$this->getFieldPosition($fieldNode)];
        }

        return $this->forms[$formId][$fieldName];
    }
778482
public function getHtml($xpath) {
    $elements = $this->findElement($xpath, 1);
    //allText works only with ONE element so it will be the first one
    return $this->browser->allHtml($elements["page_id"], $elements["ids"][0], "inner");
  }
1345729
protected function Div( $val )
	{
	    throw XPath2Exception::withErrorCodeAndParams( "XPTY0004", Resources::BinaryOperatorNotDefined,
			array(
				"op:div",
				SequenceType::WithTypeCodeAndCardinality( SequenceType::GetXmlTypeCodeFromObject( $this->_value ), XmlTypeCardinality::One ),
				SequenceType::WithTypeCodeAndCardinality( SequenceType::GetXmlTypeCodeFromObject( $val->getValue() ), XmlTypeCardinality::One )
			)
		);
	}
1046310
public function seeXmlResponseMatchesXpath($xpath)
    {
        $structure = new XmlStructure($this->connectionModule->_getResponseContent());
        $this->assertTrue($structure->matchesXpath($xpath), 'xpath not matched');
    }
933660
public function validateFragment($html)
    {
        $query = http_build_query(array_merge(
            $this->getOptions()->buildOptions(),
            array('fragment' => $html)
        ));

        $context = stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'header' => "Content-Type: application/x-www-form-urlencoded\r\nUser-Agent: HTMLValidator",
                'content' => $query,
            )
        ));

        $data = $this->sendRequest($this->validatorUri, $context);

        return $this->parseSOAP12Response($data);
    }
101147
protected function parseElement($element){
        $parsed = [];
        $this->domCrawler->filterXpath('//'.$element)->each(function($elementCrawler) use (&$parsed){
            $elementName = $elementCrawler->getNode(0)->nodeName;
            foreach($elementCrawler->getNode(0)->attributes as $attr) {
                $elementAttributes[$attr->nodeName]= $attr->nodeValue;
            }
            $parsed[$elementName]['attributes'] = $elementAttributes;
            $values = $elementCrawler->children()->each(function ($crawlerNode) use (&$parsed,$elementName){
                foreach($crawlerNode->getNode(0)->attributes as $attr)
                    $crawlerNodeAttributes[$attr->nodeName]= $attr->nodeValue;
                $parsed[$elementName]['values'][] = ['html'=>$crawlerNode->html(),'parentName'=>$crawlerNode->getNode(0)->nodeName,'parentAttributes'=>$crawlerNodeAttributes];
            });
        });
        $this->parsedElements = array_merge($this->parsedElements,$parsed);
    }
120255
protected function wrapElements($html)
    {
        if (isset($this->attributes['wraps']) && is_array($this->attributes['wraps'])) {
            $elements = $this->attributes['wraps'];
            $elements = array_reverse($elements);

            /** @var HtmlElement $element */
            foreach ($elements as $element) {
                $html = $element->setContent($html);
            }
        }

        return (string) $html;
    }
592561
private function parseNoContents(string $tag, string $html): string
    {
        $remainingHtml = \ltrim($html);
        $matchingResult = \preg_match(
            "/(<\/\s*" . $tag . "\s*>)/i",
            $html,
            $endOfScriptMatches
        );
        if ($matchingResult === 0) {
            return '';
        }

        $closingTag = $endOfScriptMatches[1];
        $this->value = \mb_substr($remainingHtml, 0, \mb_strpos($html, $closingTag));

        return \mb_substr(
            \mb_strstr($remainingHtml, $closingTag),
            \mb_strlen($closingTag)
        );
    }
593
protected function parseArgs(DOMElement $element)
    {
        $args = XmlUtil::getChildElements($element, 'arg');
        foreach ($args as $arg) {
            $name = XmlUtil::getRequiredAttributeValue($arg, 'name');
            $this->args[$name] = XmlUtil::getText($arg);
        }
    }