我正在努力让它与php一起工作。
问题是:我只是想把产品从网站上刮下来,然后把它们显示为一个产品列表,而不需要任何其他我可以在css中设置样式的东西。我想输出的是<div id='product'><a href= $link ><img src= $image /></a><br/><p>$productText</p></div>
作为一个网站的产品列表(基本上是抓取它们)。这是一个我正在尝试有趣的项目,这里是代码:
$html = new DOMDocument();
@$html->loadHtmlFile('http://www.amazon.com/gp/search/ref=sr_nr_p_8_3?rh=n%3A2619533011%2Ck%3Apet+products%2Cn%3A%212619534011%2Cn%3A2975312011%2Cp_72%3A2661618011%2Cp_8%3A2661607011&bbn=2975312011&keywords=pet+products&ie=UTF8&qid=1328429080&rnid=2661603011#/ref=sr_st?bbn=2975312011&keywords=pet+products&qid=1328429127&rh=n%3A2619533011%2Ck%3Apet+products%2Cn%3A!2619534011%2Cn%3A2975312011%2Cp_72%3A2661618011%2Cp_8%3A2661607011');
$xpath = new DOMXPath( $html );
$productName = $xpath->query( "//div[@id='btfResults']/div/div[4]/div[1]/a/text()" );
$link = $xpath->query( "//div[@id='btfResults']/div/div[3]/a/@href" );
$image = $xpath->query( "//div[@id='btfResults']/div/div[3]/a/img/@src" );
foreach ($productName as $n){
$productText = $n->nodeValue;
}
foreach ($image as $n){
$imageLink = $n->nodeValue;
}
foreach ($link as $n){
$linkLink = $n->nodeValue;
}
foreach ($link as $n)
{
echo "<div id='product'><a href= $linkLink ><img src= $imageLink /></a><br/><p>$productText</p></div>";
}
事实上,我不知道如何得到我想要的正确结果。如果需要进一步解释,请告诉我。谢谢
修复并测试:
<?php
$html = new DOMDocument();
@$html->loadHtmlFile('http://www.amazon.com/gp/search/ref=sr_nr_p_8_3?rh=n%3A2619533011%2Ck%3Apet+products%2Cn%3A%212619534011%2Cn%3A2975312011%2Cp_72%3A2661618011%2Cp_8%3A2661607011&bbn=2975312011&keywords=pet+products&ie=UTF8&qid=1328429080&rnid=2661603011#/ref=sr_st?bbn=2975312011&keywords=pet+products&qid=1328429127&rh=n%3A2619533011%2Ck%3Apet+products%2Cn%3A!2619534011%2Cn%3A2975312011%2Cp_72%3A2661618011%2Cp_8%3A2661607011');
$xpath = new DOMXPath( $html );
$btfResults = $xpath->query("//div[@id='btfResults']/div"); // get all item nodes
foreach ($btfResults as $node) // iterate through all items
{
$productText = $linkLink = $imageLink = null; // reset result variables for each loop
if ($productName = $xpath->query("./div[4]/div[1]/a/text()", $node)->item(0)) // fetch productName node from the item
{
$productText = $productName->nodeValue;
}
if ($link = $xpath->query("./div[3]/a/@href", $node)->item(0)) // fetch link node from the item
{
$linkLink = $link->nodeValue;
}
if ($image = $xpath->query("./div[3]/a/img/@src", $node)->item(0)) // fetch image node from the item
{
$imageLink = $image->nodeValue;
}
if ($productText && $linkLink && $imageLink) // only return a result when all variables are set.
{
echo '<div id="product"><a href="'.$linkLink.'"><img src="'.$imageLink.'"/></a><br/><p>'.$productText.'</p></div>';
}
}