PHP Simple HTML DOM Parser查找具有多个属性的元素

时间:2013-04-18 09:07:10

标签: php web-scraping simple-html-dom

我正在使用Simple HTML DOM Parser,但无法弄清楚如何获得以下内容:

想象一下,我有这个:

<td style"color:#e05206" width"22" height="58">OK</td>
<td style"color:#e05206" width"22" height="58" align="center">NOT OK</td>
<td style"color:#ffffff" width"22" height="58">NOT OK</td>

我想好起来。

我试过这样的事情:

$results = $html->find('td[style*=color:#e05206], td[width*="22"], td[height*=58], td[!align]');

我认为这是正确的答案,但事实并非如此,因为它应用了OR而不是AND

我想只获得好而不是所有元素。 总结一下,我想要有V和X和Y而不是Z的td。 有可能吗?

感谢您的回答!

更新 我没有找到好的,它可能是其他任何东西。 我正在寻找一个td,它有一个属性V = something AND X = something AND Y = something AND NOT Z。

4 个答案:

答案 0 :(得分:0)

var OkElement = new Array();
$("table tr").find("td").each(function(){
   tdValue = $(this).text();
   if(tdValue == "OK"){
      OkElement.push($(this).attr('id');
   }
});

说明:这里我们循环所有td DOM元素,然后检查OK Value。 对于每个循环,这表示当前的td元素并获取td值并检查文本值是否正常,如果它是OK值,那么我们将td elemtnt ID推送到数组中。 finally数组只包含包含OK文本的td元素ID。 注意:您应该为每个td元素指定唯一ID。

    <td id="x1" style"color:#e05206" width"22" height="58">OK</td>
    <td id="x2" style"color:#e05206" width"22" height="58" align="center">NOT OK</td>
    <td id="x3" style"color:#ffffff" width"22" height="58">NOT OK</td>

因为虽然你得到了td元素,但是你不能操纵相应的td元素而没有id。 现在,您将在OkElement数组中获得x1,现在您可以按照您希望的示例

来操作该div
for(var i=0;i<OkElement.length;i++){
    $("#"+OkElement[i]).attr('style','background-color : red');
}

在我的示例中,我将背景颜色红色应用于具有OK

的td元素

答案 1 :(得分:0)

var OkElement = new Array();
$("table tr").find("td").each(function(){
   tdValue = $(this).text();
   if(tdValue == "OK"){
      OkElement.push($(this).css('color')
   }
});

Explanation : Here We are looping all the td DOM Elements and then checking for OK Value.
    for Each loop this indicates current td elements and getting the td value and checking whether text value is OK or not if it is OK value then we pushing the td elemtnt color style into array...
    Finally array contains only #e05206 which contains OK text. 





    Now you will get #e05206 in OkElement Array now you can manipulate that tds as you wish
    Example 

答案 2 :(得分:0)

理想情况下,您希望能够通过以下方式获得该目标:

'td:not([align])[style="color:#e05206"]'

'td[style="color:#e05206"]:not([align])'

你不能用简单的html dom做到这一点,因为很简单。

好消息是你可以用phpquery做到。

答案 3 :(得分:0)

好的,这就是我所做的。

我使用了ganon lib。

$results = $html('td[style + width + height + !align]');

lib几乎可以处理所有事情。

https://code.google.com/p/ganon/