如何使用 DOMparser/Xpath 在 div 下抓取 DL 的 DT 和 DD [英] How to web-scrape DL's DT and DD which is under a div with DOMparser/Xpath

查看:70
本文介绍了如何使用 DOMparser/Xpath 在 div 下抓取 DL 的 DT 和 DD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取属于类的 DL 的 DT 和 DD,并尝试将它们放在 foreach 中.但是遇到了一些麻烦,

I am trying to get DL's DT and DD which is under a class and trying to put those in a foreach. But facing some troubles,

<dl class="c-explain2">
        <dt>所在地</dt>
                <dd>
                    大阪府大阪市 北区天満1丁目25番1(地番)
                        <br>

这是我的代码;

$DOMParser = new \DOMDocument();
$DOMParser->loadHTML($html);
$xpath = new \DOMXPath($DOMParser);

$classname="c-explain2";
$getAllTable = $xpath->query("//dl[contains(@class, '$classname')]//");

foreach($getAllTable as $table){
            $allProperties = [];

            $table->getElementsByTagName('dt')[0]->nodeValue;

            $value = $table->getElementsByTagName('dd')[0]->nodeValue;
            $allProperties[] = [
                    'property' => $property, 
                    'value'=> $value];
            }
                $insertData[$start_id] = $allProperties;
                $MyTable = true; 

如何得到那些 dt 和 dd,然后想把它们放在数组中.有什么帮助吗?谢谢你.

How to get those dt and dd, After that want to put those in array. Any help? Thank you.

推荐答案

你的XPath表达式有问题,应该是"//dl[@class='$classname']"

There is a problem with your XPath expression, it should be "//dl[@class='$classname']"

此外,您似乎从未在循环中分配 $property .试试这个:

Also it looks like you are never assigning $property in your loop. Try this:

<?php
$html = <<<END
<dl class="c-explain2">
        <dt>所在地</dt>
        <dd>大阪府大阪市 北区天満1丁目25番1(地番</dd>
</dl>
END;

$DOMParser = new \DOMDocument();
$DOMParser->loadHTML($html);
$xpath = new \DOMXPath($DOMParser);

$classname   = "c-explain2";
$getAllTable = $xpath->query("//dl[@class='$classname']");

foreach ($getAllTable as $table)
{
    $allProperties = [];

    $property = $table->getElementsByTagName('dt')[0]->nodeValue;

    $value           = $table->getElementsByTagName('dd')[0]->nodeValue;
    $allProperties[] = [
        'property' => $property,
        'value' => $value
    ];
}

这篇关于如何使用 DOMparser/Xpath 在 div 下抓取 DL 的 DT 和 DD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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