【发布时间】:2021-05-30 13:08:53
【问题描述】:
前言:这是我编写的第一个 XPath 和 DOM 脚本。
以下代码在一定程度上有效。
如果应该是 price 的 child->nodevalue 为空,它会丢弃其余元素,然后从那里滚雪球。我花了好几个小时阅读、重写,却想不出办法来解决它。
我认为我的 XPath 查询可能是问题所在,因为我不知道如何测试这是正确的子值。
我正在抓取的内容看起来像这样(实际上它看起来不像这样,每个产品都有 148 行 HTML,但这些是相关的):
<div class="some really long class name">
<h2 class="second class">
<a class="a-link-normal s-no-outline" href="TheURLINeed.php">
<span class="a-size-base-plus a-color-base a-text-normal">
The Title I Need
</span>
</a>
</h2>
<span class="a-offscreen">
$1,000,000
</span>
</div>
这是我正在使用的代码。
$html =file_get_contents('http://localhost:8888/scraper/source.html');
$doc = new \DOMDocument();
$doc->loadHTML($html);
$xpath = new \DOMXpath($doc);
$xpath->preserveWhiteSpace = FALSE;
$nodes= $xpath->query("//a[@class = 'a-link-normal s-no-outline'] | //span[@class = 'a-size-base-plus a-color-base a-text-normal'] | //span[@class = 'a-price']");
$data =[];
foreach ($nodes as $node) {
$url = $node->getAttribute('href');
if(trim($url,"\xc2\xa0 \n \t \r") != ''){
array_push($data,$url);
}
foreach ($node->childNodes as $child) {
if (trim($child->nodeValue, "\xc2\xa0 \n \t \r") != '') {
array_push($data, $child->nodeValue);
}
}
}
$chunks = (array_chunk($data, 4));
foreach($chunks as $chunk) {
$newarray = [
'url' => $chunk[0],
'title' => $chunk[1],
'todaysprice' => $chunk[2],
'hiddenprice' => $chunk[3]
];
echo '<p>' . $newarray['url'] . '<br>' . $newarray['title'] . '<br>' .
$newarray['todaysprice'] . '</p>';
}
输出:
URL
Title
Price
URL
Title
Price
URL
Title
URL. <---- "Price was missing so it used the next child node value and now everything from here down is wrong."
Title
Price
URL
我知道这段代码离右边很远,但我必须从某个地方开始。
【问题讨论】:
-
您能否编辑您的问题并添加一个示例,其中缺少价格以及两种情况下预期的确切输出?
-
它就在那里,在输出下,请参阅底部部分,它说 PRICE WAS MISSING 所以它使用了下一个孩子。并且没有价格的产品只是将 span a-offscreen 留空。
-
我看到了;我指的是一个缺少价格的输入示例(即另一个
<div>元素)。知道它长什么样会很有用。 -
他们只是将 完全排除在 html 之外。
-
我认为这就是我需要更改查询的原因...拉取周围 div 的内容,在示例中,检查包含 price 的跨度,如果不存在则跳到下一个....我想!就像我说的那样,我对此很陌生。
标签: php dom web-scraping xpath