Files
karudhaas/app/Services/Scrapers/MihaaruScraper.php
2024-01-13 04:53:31 +05:00

82 lines
2.3 KiB
PHP

<?php
namespace App\Services\Scrapers;
use Goutte\Client;
use Symfony\Component\HttpClient\HttpClient;
class MihaaruScraper
{
protected $client;
protected $title;
protected $content;
protected $image;
protected $topics = [];
protected $author;
public function __construct()
{
$this->client = new Client(
HttpClient::create([
"proxy" => config('karudhaas.proxy.host')
])
);
}
public function extract($url, $date = null)
{
$crawler = $this->client->request('GET', $url);
$crawler->filter('h1')->each(function ($node) {
$this->title = $node->text();
});
$this->image = $crawler->filter('.w-full.flex.flex-col.items-end.max-w-3xl.mb-10.relative img')->attr('src');
$crawler->filter('.by-line address')->each(function ($node) {
$author = $node->text();
//Trim all the white spaces
$spacetrim = str_replace(' ', '', $author);
//Replace multiple spaces and newlines with a single space
$cleaneddata = trim(preg_replace('/\s\s+/', ' ', $spacetrim));
$this->author = $cleaneddata;
});
$crawler->filter('.text-faseyha')->each(function ($node) {
$this->content[] = $node->text();
});
$crawler->filter('.items-end a')->each(function ($node) {
try {
$topicName = $node->filter('span')->text();
$topicSlug = ltrim($node->attr('href'), '/');
} catch (\Throwable $th) {
return;
}
$this->topics[] = [
"name" => $topicName,
"slug" => $topicSlug
];
});
//Remove all the alphabets from string
//preg_replace("/[a-zA-Z]/", "",$string);
return [
'source' => 'Mihaaru',
'title' => $this->title,
'og_title' => $crawler->filter('meta[property*="og:title"]')->first()->attr('content'),
'image' => $this->image,
'content' => $this->content,
'url' => $url,
'date' => $date,
'guid' => str_replace("https://mihaaru.com/news/", "", $url),
'author' => $this->author,
'topics' => $this->topics
];
}
}