首页 > 解决方案 > php goutte web scraper 不时给出不同的结果

问题描述

我正在尝试为亚马逊的产品页面构建一个网络爬虫。

我决定使用 Goutte 库(基于这个 freeCodeCamp 教程)。

到目前为止,这是我编写的代码:

<?php
    require 'vendor/autoload.php';

    $link = readline('Enter the product you want to scrape: ');

    $httpClient = new \Goutte\Client();
    $response = $httpClient->request('GET', $link);
    
    $title_ = $response->evaluate('//span[@id="productTitle"]');
    $price_ = $response->evaluate('//span[@class="priceBlockStrikePriceString a-text-strike"]');
    $offer_ = $response->evaluate('//span[@id="priceblock_ourprice"]');

    foreach ($title_ as $key => $title) {
        $str = $title->textContent . PHP_EOL;
        $str = str_replace("\n","",$str);
        echo $str , "\n";
    }

    foreach ($price_ as $key => $price) {
        $str = $price->textContent . PHP_EOL;
        $str = str_replace(array("\n", " "),"",$str);
        echo $str , "\n";
    }

    foreach ($offer_ as $key => $offer) {
        $str = $offer->textContent . PHP_EOL;
        $str = str_replace(array("\n", " "),"",$str);
        echo $str , "\n";
    }
?>

如您所见,我正在尝试提取产品的标题、列出的价格和亚马逊的报价。

真正让我感到沮丧的是,上面的代码有时有效,有时无效。

例如,我通过给它这个链接来测试它。

有时我会得到想要的结果:

Amazon Basics Liquid Crystal Clear Soft TPU Smartphone Cover for iPhone 13 Pro Max
$9.99
$6.69

但后来我又试了一次,没有改变任何东西,我只得到了产品的标题:

Amazon Basics Liquid Crystal Clear Soft TPU Smartphone Cover for iPhone 13 Pro Max

这是怎么回事?我猜我的代码有问题(我是网络抓取的新手),有人可以帮忙吗?提前致谢。

标签: phpweb-scrapinggoutte

解决方案


推荐阅读