php Symfony DomCrawler:查找具有特定属性值的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16300958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:53:19  来源:igfitidea点击:

Symfony DomCrawler: Find element with specific attribute value

phpdomsymfonyhtml-parsing

提问by Wesley

I'm using the DomCrawler component: http://symfony.com/doc/current/components/dom_crawler.html

我正在使用 DomCrawler 组件:http://symfony.com/doc/current/components/dom_crawler.html

I'd like to, using the CSS like syntax, get an element with a specific attribute value.

我想使用类似 CSS 的语法,获取具有特定属性值的元素。

Here's the code I'm using:

这是我正在使用的代码:

$link = $crawler->filter('#product a[data-type="bla"]');

This seems to work, as the following returns 1:

这似乎有效,因为以下返回 1:

echo count($link);

However, I can never not filter further than this. I can not do:

但是,我永远不能比这更进一步过滤。我不能做:

$link->filter('img')->attr('src'); 

This results in the following error message:

这会导致以下错误消息:

The current node list is empty.

However, I know for certain that it isn't.

但是,我确信它不是。

I've tried the syntax on other elements and it's always the same. I am doing something wrong or is this not possible (with css like syntax, not xpath)

我已经尝试过其他元素的语法,它总是一样的。我做错了什么或者这是不可能的(使用类似 css 的语法,而不是 xpath)

回答by M8R-1jmw5r

I can not follow your problem. Using the current development versions (and also 2.1.0 and 2.2.0 versions) of the twosoftware libraries dom-crawlerand css-selector, the example code you provided works just fine considering the following example HTML:

我无法解决你的问题。使用两个软件库dom-crawlercss-selector的当前开发版本(以及 2.1.0 和 2.2.0 版本),考虑到以下示例 HTML,您提供的示例代码工作得很好:

<?php
use Symfony\Component\DomCrawler\Crawler;

// require dependencies here    

$html = <<<'HTML'
<!DOCTYPE html>
<html>
    <body>
        <p class="message">Hello World!</p>
        <p>Hello Crawler!</p>
        <div id="product">
            <a data-type="bla">
                <img src="OK">
            </a>
        </div>
    </body>
</html>
HTML;

$crawler = new Crawler($html);

$link = $crawler->filter('#product a[data-type="bla"]');

echo var_dump(count($link));

var_dump($link->filter('img')->attr('src'));

As you can see this is exactly your code (only a little different but essentially not), which gives the following output verbatim:

正如您所看到的,这正是您的代码(只有一点不同,但基本上没有),它逐字提供以下输出:

int(1)
string(2) "OK"

The first output line is the count()and the second is the src attribute value.

第一个输出行是 the count(),第二个是 src 属性值。

Have you run composer update? Have you double-checked the input?

你有没有运行作曲家更新?您是否仔细检查了输入?