通过TH,domCrawler定位TD位置

时间:2019-10-15 02:10:34

标签: php web-scraping domcrawler

我正在尝试抓取table的{​​{1}}标记,但是首先我需要检查td。例如,假设表结构如下。

th

在此表中,我需要抓取<tbody> <tr> <th>color</th> <td>red</td> </tr> <tr> <th>price</th> <td>23.267$</td> </tr> <tr> <th>brand</th> <td>mustang</td> </tr> </tbody> 值。但是我不能为此使用mustang。因为位置总是在变化。因此,我需要使用$crawler->filter('table td')->eq(3);来获取值。我的意思是,如果th的价值是 brand ,那么得到的是th

什么是最好的方法?

1 个答案:

答案 0 :(得分:0)

不确定这是最佳解决方案,但我通过以下方法解决了该问题:

$props = $node->filter("table th")->each(function($th, $i){
    return $th->text();
});
$vals = $node->filter("table td")->each(function($td, $i){
    return $td->text();
});

$items = [
    "brand" => "", 
    "color" => "",
];

for ($a=0; $a < count($props); $a++) { 
    switch ($props[$a]) {
        case 'brand':
            $items["brand"] = $vals[$a];
            break;                        
    }
}

如果有另一种方法或更好的方法可以实现这一目标。请随时在这里发布。谢谢。