Php 为什么';这个简单的html dom选择器在整体使用时不能工作,但在分解成更小的选择器时不能工作吗?
我正试着用它刮一页纸。在我正在抓取的页面上,有一张表格,上面有行,里面有一堆单元格。我想在每一排的第三个牢房里拿些东西。所讨论的单元格没有类Php 为什么';这个简单的html dom选择器在整体使用时不能工作,但在分解成更小的选择器时不能工作吗?,php,dom,simple-html-dom,Php,Dom,Simple Html Dom,我正试着用它刮一页纸。在我正在抓取的页面上,有一张表格,上面有行,里面有一堆单元格。我想在每一排的第三个牢房里拿些东西。所讨论的单元格没有类 <tr class="thisrow"> <td class="firstcell"><strong>1st</strong></td> <td class="secondcell">nothing in here</td> <td><stro
<tr class="thisrow">
<td class="firstcell"><strong>1st</strong></td>
<td class="secondcell">nothing in here</td>
<td><strong>blah blah</strong></td>
<td>something else</td>
</tr>
但后来我意识到我需要行中另一个单元格(td.firstcell)中的一些数据。此单元格有一个类,因此我认为最好在行中循环,然后在该行的上下文中使用选择器:
foreach($html->find('tr.thisrow') as $row) {
$thirdcell = $row->find('td:nth-child(3)');
echo $thirdcell; // this is now empty
$firstcell = $row->find('td.firstcell');
echo $firstcell; // this works!
}
如您所见,行循环上下文中的第n个子选择器突然不起作用。我缺少什么?您可以使用children($int)
方法<代码>$int以0
开头
试试这个:
$row = $html->find('tr.thisrow',0);
$firstcell = $row->children(2)->innertext;
$thirdcell = $row->children(0)->innertext;
还有:first\u child()
,last\u child()
,parent()
,next\u sibling()
,prev\u sibling()
,您可以使用children($int)
方法<代码>$int以0
开头
试试这个:
$row = $html->find('tr.thisrow',0);
$firstcell = $row->children(2)->innertext;
$thirdcell = $row->children(0)->innertext;
还有:
first\u child()
,last\u child()
,parent()
,next\u sibling()
,prev\u sibling()
这是简单html dom的一个限制。显然,它可以处理第n个子
选择器,但仅当父节点位于应用find
的节点下方的树中时
但它是一个有效的选择器,正如等价的JavaScript所示:
for(变量行[…document.querySelectorAll('tr.thisrow')){
var thirdcell=row.querySelectorAll('td:n第n个子项(3)');
console.log(thirdcell[0].textContent);//这很有效!
}
1st
这里什么都没有
胡说八道
别的
这是简单html dom的一个限制。显然,它可以处理第n个子
选择器,但仅当父节点位于应用find
的节点下方的树中时
但它是一个有效的选择器,正如等价的JavaScript所示:
for(变量行[…document.querySelectorAll('tr.thisrow')){
var thirdcell=row.querySelectorAll('td:n第n个子项(3)');
console.log(thirdcell[0].textContent);//这很有效!
}
1st
这里什么都没有
胡说八道
别的
您可以添加目标html进行测试吗?@smoqadam,当然可以,谢谢,我添加了它。您可以添加目标html进行测试吗?@smoqadam,当然可以,谢谢,我添加了它。感谢您解释这一点,并教给我们一种非常好的方法来检查我的选择器是否正确!我从来没有想到这是软件包中的一个限制。谢谢你的解释,也教了一个很好的方法来检查我的选择器是否正确!我从未想到这是包装中的一个限制。