【问题标题】:How to select a link using its id or its label with the symfony dom crawler?如何使用 symfony dom 爬虫使用其 id 或标签来选择链接?
【发布时间】:2019-08-07 14:59:48
【问题描述】:

是否可以通过 symfony 爬虫使用它的 id 或它的类来选择一个链接?

我试过了:

$crawler()->selectLink('#return-button')->link();
$crawler()->selectLink('.btn.return')->link();

但我有错误:

InvalidArgumentException:当前节点列表为空。

选择器是否只能使用a 标签的内容?

【问题讨论】:

    标签: php symfony symfony4 domcrawler


    【解决方案1】:

    是的,如果您的链接是图片,它仅适用于链接文本或alt 属性。

    filter() 方法使用CssSelector 组件将选择器转换为XPath 表达式,然后像selectLink() 一样调用filterRelativeXPath(),因此它们返回相同的类型,您应该可以调用

    $crawler->filter('#return-button')->link();
    

    如果类选择器返回多个匹配项,由于link() 仅适用于第一个节点,因此您需要调用links()

    $crawler->filter('.btn.return')->links();
    

    【讨论】:

      【解决方案2】:

      我不这么认为:

      public selectLink ( string $value ) : Crawler
      

      其中 $value 是作为链接文本的字符串:

      symfony.component.domcrawler/Crawler/selectLink

      但你可以试试:

      $crawler->filter('body')->children('a.lorem')->attr('href'); //if you need the link
      

      或者可能,这适用于 id:

      $crawler->filter('body')->children('a@foo');
      

      你应该自己弄清楚,如果检查这个:

      symfony/components/dom_crawler

      【讨论】:

        【解决方案3】:

        试试这个:

        $myLink = $crawler->filter('#return-button')->text();
        $myLink = $crawler->filter('.btn.return')->text();
        

        这将返回链接或按钮文本,然后:

        $crawler()->selectLink($myLink)->link();
        

        这确实比通过文本选择链接要好。祝你好运:-)

        【讨论】:

        • 感谢您的评论!遗憾的是它不起作用,我想是因为我的链接中有一个图标标签,并且当它包含 HTML 时,爬虫无法selectLink
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-30
        • 2023-03-10
        • 1970-01-01
        • 2010-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多