【发布时间】:2020-03-05 13:40:48
【问题描述】:
我似乎无法找到如何使用 xpath 获取 html 页面的值。我正在尝试检索页面上每个产品的图像源、价格和名称...我可以检索产品的数量,但之后不知何故无法获得任何值...我绝对不是一个专业人士,可以解释一下;)
我尝试了一些东西。我可以在 Chrome 中看到 xpath 并尝试使用它们,但它总是空的。在这一点上,我不知道该尝试什么。
<div class="prod-main">
<div class="prod-thumb text-center" data-id="1948348">
<div class="prod-thumb-16-9">
<a href="#"><img class="lazy" alt="" src="image.jpg"></a>
</div>
</div>
<div class="prod-info">
<span class="prod-price">$8.00</span>
<span class="prod-title"><a href="#">Product Name</a></span>
</div>
</div>
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$newDom = new domDocument;
$html=url_get_contents('test.html');
$newDom->loadHTML($html);
$newDom->preserveWhiteSpace = false;
$finder = new DomXPath($newDom);
$products = $finder->query('//div[@class="prod-main"]');
foreach($products as $product) {
$img = $finder->query('/div[2]/div/a/img/@src', $clip)[0]->value;
}
phparray(24) { [0]=> NULL [1]=> NULL [2]=> NULL [3]=> NULL [4]=> NULL [5]=> NULL [6]=> NULL [7]=> NULL [8]=> NULL [9]=> NULL [10]=> NULL [11]=> NULL [12]=> NULL [13]=> NULL [14]=> NULL [15]=> NULL [16]=> NULL [17]=> NULL [18]=> NULL [19]=> NULL [20]=> NULL [21]=> NULL [22]=> NULL [23]=> NULL }
【问题讨论】: