0

我正在拉扯我的头发,试图让它与 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>";
}

事实是我不知道如何获得我想要的正确结果。让我知道这是否需要进一步解释。谢谢!

4

1 回答 1

0

固定和测试:

<?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>';
    }
}
于 2012-02-29T11:49:11.157 回答