【问题标题】:Is it possible to search by regexp with Symfony Dom crawler?是否可以使用 Symfony Dom 爬虫通过正则表达式进行搜索?
【发布时间】:2019-07-18 21:39:10
【问题描述】:

Dom Crawler Component 可以强大地解析 html 内容,在其文档中描述了基本选择(如 filter('body > p'))或更复杂的 xpath,如 //span[contains(@id, "article-")]

是否可以通过正则表达式获取元素?也许可以使用类似的东西:filter('body')->filter('div.*-timeLabel-*')

【问题讨论】:

    标签: symfony parsing dom domcrawler


    【解决方案1】:

    在 XPath 2.0 中,您可以使用匹配项:

    $crawler->filterXPath("//div[matches(@id, '*-timeLabel-*')]");
    

    但如果您没有可用的,最好的办法是尝试结合其他一些 XPath methods,例如,这应该可以解决您的情况:

    $crawler->filterXPath("//div[contains(@id, '*-timeLabel-*')]");
    

    【讨论】:

      【解决方案2】:

      我不确定,但我认为答案是肯定的,因为爬虫调用的过滤方法 CssSelectorConverter 的这种方法,根据文档,您可以将表达式作为参数传递

          /**
           * Translates a CSS expression to its XPath equivalent.
           *
           * Optionally, a prefix can be added to the resulting XPath
           * expression with the $prefix parameter.
           *
           * @param string $cssExpr The CSS expression
           * @param string $prefix  An optional prefix for the XPath expression
           *
           * @return string
           */
          public function toXPath($cssExpr, $prefix = 'descendant-or-self::')
          {
              return $this->translator->cssToXPath($cssExpr, $prefix);
          }
      

      【讨论】:

        【解决方案3】:

        这样的?修改了应用匿名函数的文档中的一个示例。

        $nodeValues = $crawler->filter('body')->each(function (Crawler $node, $i) {
            // regex and return $node->attr('class')
        });
        

        【讨论】:

          猜你喜欢
          • 2015-09-22
          • 1970-01-01
          • 2023-02-08
          • 2012-05-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-03
          • 1970-01-01
          相关资源
          最近更新 更多