我需要使用 Dom 和 XPath 从电子商务网站提取特定产品的价格并将其保存到 MySQL 数据库。
我已经尝试过
<?php
$html = new DOMDocument();
@$html->loadHtmlFile('http://www.flipkart.com/samsung-galaxy-star-pro-s7262/p/itmdqq6zfh7y7enm?pid=MOBDQ22YUJ8ZFXKW&srno=b_1&ref=0545bfb1-043b-479f-aca2-a468e03f0c34');
$xpath = new DOMXPath( $html );
*$nodelist = $xpath->query("id('topsection')/x:div[3]/x:div[2]/x:div[1]/x:div/x:div[1]/x:div/x:span");*
foreach ($nodelist as $n){
echo $n->nodeValue."\n";
}
?>
此代码适用于获取网址、页面标题等内容。
但是当我尝试使用它通过 xpath 从该特定网址获取价格时,它什么也没得到。可能出了什么问题?
最佳答案
由于该网站使用一些微数据,您可以在查询中使用这些数据。
这样您将减少对标记结构的依赖:
$query = $xpath->query("//*[contains(@itemprop, 'price')]");
//loop over the results accessing the content attribute
foreach ($query as $result) {
var_dump($result->getAttribute('content'));
}
//or
echo sprintf(
"%s %s",
$query->item(0)->getAttribute('content'),
$query->item(1)->getAttribute('content')
);
参见http://dev.w3.org/html5/md-LC/ & http://schema.org/docs/gs.html欲了解更多信息:
关于php - 需要使用 xpath 从电子商务网站抓取价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21753231/