【发布时间】:2012-10-15 20:55:51
【问题描述】:
我正在使用 Curl、XPath 和 PHP 来从 HTML 源代码中抓取产品名称和价格。这是一个类似于我正在检查的源代码的示例:
<div class="Gamesdb">
<p class="media-title">
<a href="/Games/Console/4-/105/Bluetooth-Headset/">Bluetooth Headset</a>
</p>
<p class="sub-title"> Console </p>
<p class="rating star-50">
<a href="/Games/Console/4-/105/Bluetooth-Headset/ProductReviews.html">(1)</a>
</p>
<p class="mt5">
<span class="price-preffix">
<a href="/Games/Console/4-/105/Bluetooth-Headset/">1 New</a>
from
</span>
<a class="wt-link" href="/Games/Console/4-/105/Bluetooth-Headset/">
<span class="price">
<em>£34</em>
.99
</span>
<span class="free-delivery"> FREE delivery</span>
</a>
</p>
<p class="mt10">
<a class="primary button" href="/Games/Console/4-/105/Bluetooth-Headset/">
Product Details
<span style="color: rgb(255, 255, 255); margin-left: 6px; font-size: 16px;">»</span>
</a>
</p>
</div>
我想提取媒体标题,即:
<p class="media-title">
<a href="/Games/Console/4-/105/Bluetooth-Headset/">Bluetooth Headset</a>
</p>
仅当以下价格等级也存在时:
<span class="price">
<em>£34</em>
.99
</span>
列出的许多其他产品不包括它。 我需要提取产品名称和价格,或者什么都不提取,然后转到下一个产品。
这是我当前使用的代码示例,无论其他条件如何,它都能有效地获取所有结果:
$results=file_get_contents('SCRAPEDHTML.txt');
$html = new DOMDocument();
@$html->loadHtml($results);
$xpath = new DOMXPath($html);
$nodelist = $xpath->query('//p[@class="media-title"]|//span[@class="price"]');
foreach ($nodelist as $n){
$results2[]=$n->nodeValue;
}
我相信使用正确的 xpath 查询可以做到这一点,但到目前为止还无法实现。非常感谢。
【问题讨论】:
-
鉴于 html 示例和代码示例,您现在使用的 XPath 不应返回 any 结果...
-
为了避免不必要的冗长,源示例被稍微简化了,我编辑了我的代码示例,添加了分隔符“|”到由于我的错误而被省略的 xpath 查询。
-
您要提取什么?节点或只是文本
Bluetooth Headset和£34.99? -
只是文字:蓝牙耳机和 34.99 英镑。但前提是两者都存在,因为这只是网站上列出的许多其他产品的一小部分,其中许多不包括价格。
-
试试这个表达式
//div[p/@class='media-title'][//span/@class='price']//*[@class='media-title' or @class='price']//text()它并不完美,它的工作方式取决于代码在实际页面上的结构。它应该让您足够接近解决方案。它选择了一些不必要的文本节点,这些节点可以通过使用 XPath 2.0 函数或通过处理 php 中的结果集来删除。
标签: php xpath web-scraping