php - 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
这是怎么回事?我猜我的代码有问题(我是网络抓取的新手),有人可以帮忙吗?提前致谢。
解决方案
推荐阅读
- python - 用于查找素数因子的 python 代码中的语法错误。如果有人可以帮助我,我将不胜感激
- batch-file - Jenkins 中的参数化 Buid Step 命令
- python - 使用 python 和 ascii 值创建随机密码
- java - 以纳秒为单位查找每个 Fibonacci(n) 的时钟时间
- swiftui - TextEditor 在 SwiftUI 中坚持 minHeight
- charts - Highcharts 为水墙和堆栈柱形图创建图例
- javascript - Angular mat-table 重置数据源而不重置页面
- python - 当我使用 BeautifulSoup 从该网站上抓取价格时,为什么当我按下检查时输出与 html 代码不匹配?
- kubernetes - 如何保持 redis 数据库 pod 在 kubernetes 中运行
- performance-testing - 如何使用 Gatling 在封闭模型中实现恒定的并发活跃用户?