PHP - 抓取所有 trustpilot 评论的数据

PHP - Scrape data of all trustpilot reviews

<?php 
for ($x = 0; $x <= 25; $x++) {

$ch = curl_init("https://uk.trustpilot.com/review/example.com?languages=all&page=$x");
//curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout in seconds
$trustpilot = curl_exec($ch);

// Check if any errorccurred
if(curl_errno($ch))
{
     die('Fatal Error Occoured');
}

} 
?>

此代码将获取 example.com 的所有 25 页评论,然后我想做的是将所有结果放入 JSON 数组或其他内容中。

我尝试了以下代码,以便检索所有名称:

<?php
$trustpilot = preg_replace('/\s+/', '', $trustpilot); //This replaces any spaces with no spaces
$first = explode( '"name":"' , $trustpilot );
$second = explode('"' , $first[1] );
$result = preg_replace('/[^a-zA-Z0-9-.*_]/', '', $second[0]);    //Don't allow special characters

?>

这显然比我预期的要难得多,有谁知道我如何才能将所有评论都放入 JSON 或其他内容,无论我选择多少页,例如在这种情况下我选择 25值得评论的页数。

谢谢!

do not parse HTML with regex.

使用 DOMDocument 和 DOMXPath 解析它们。此外,您为每个页面创建一个新的 curl 句柄,但您永远不会关闭它们,这是代码中的 resource/memory 泄漏,而且也是对 cpu 的浪费,因为您 可以 一遍又一遍地重复使用相同的 curl 句柄(而不是为每个页面创建一个新的 curl 句柄,这需要 cpu ), 提示: 这个 html 压缩得很好, 所以你应该使用 CURLOPT_ENCODING 下载压缩后的页面, 例如:

<?php
declare(strict_types = 1);
header("Content-Type: text/plain;charset=utf-8");
$ch = curl_init();
curl_setopt($ch, CURLOPT_ENCODING, ''); // enables compression
$reviews = [];
for ($x = 0; $x <= 25; $x ++) {
    curl_setopt($ch, CURLOPT_URL, "https://uk.trustpilot.com/review/example.com?languages=all&page=$x");
    // curl_setopt($ch, CURLOPT_POST, true);
    // curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); // timeout in seconds
    $trustpilot = curl_exec($ch);

    // Check if any errorccurred
    if (curl_errno($ch)) {
        die('fatal error: curl_exec failed, ' . curl_errno($ch) . ": " . curl_error($ch));
    }
    $domd = @DOMDocument::loadHTML($trustpilot);
    $xp = new DOMXPath($domd);
    foreach ($xp->query("//article[@class='review-card']") as $review) {
        $id = $review->getAttribute("id");
        $reviewer = $xp->query(".//*[@class='content-section__consumer-info']", $review)->item(0)->textContent;
        $stars = $xp->query('.//div[contains(@class,"star-item")]', $review)->length;
        $title = $xp->query('.//*[@class="review-info__body__title"]', $review)->item(0)->textContent;
        $text = $xp->query('.//*[@class="review-info__body__text"]', $review)->item(0)->textContent;
        $reviews[$id] = array(
            'reviewer' => mytrim($reviewer),
            'stars' => ($stars),
            'title' => mytrim($title),
            'text' => mytrim($text)
        );
    }
}
curl_close($ch);
echo json_encode($reviews, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | (defined("JSON_UNESCAPED_LINE_TERMINATORS") ? JSON_UNESCAPED_LINE_TERMINATORS : 0) | JSON_NUMERIC_CHECK);


function mytrim(string $text): string
{
    return preg_replace("/\s+/", " ", trim($text));
}

输出:

{
    "4d6bbf8a0000640002080bc2": {
        "reviewer": "Clement Skau Århus, DK, 3 reviews",
        "stars": 5,
        "title": "Godt fundet på!",
        "text": "Det er rigtig fint gjort at lave et example domain. :)"
    }
}

因为您列出的 url 这里只有 1 条评论。 4d6bbf8a0000640002080bc2 是该评论的网站内部 ID(可能是 sql 数据库 ID)。