Symfony DomCrawler:查找具有特定属性值的元素 [英] Symfony DomCrawler: Find element with specific attribute value

查看:419
本文介绍了Symfony DomCrawler:查找具有特定属性值的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

以下是我使用的代码:

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

这似乎工作,因为以下返回1:

This seems to work, as the following returns 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.

我已经尝试过其他元素的语法,它总是一样的。我正在做错事,或者这是不可能的(用css语法,而不是xpath)

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)

推荐答案

我无法按照你的问题。使用 两个 软件库的现有开发版本(以及2.1.0和2.2.0版本),dom-crawler 和 css-selector ,您提供的示例代码可以很好地考虑以下示例HTML: p>

I can not follow your problem. Using the current development versions (and also 2.1.0 and 2.2.0 versions) of the two software libraries dom-crawler and css-selector, the example code you provided works just fine considering the following example 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"

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

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

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

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

这篇关于Symfony DomCrawler:查找具有特定属性值的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆