diff --git a/app/Console/Commands/ScrapeDhenCommand.php b/app/Console/Commands/ScrapeDhenCommand.php new file mode 100644 index 0000000..f8ae5e4 --- /dev/null +++ b/app/Console/Commands/ScrapeDhenCommand.php @@ -0,0 +1,72 @@ +first(); + + $articles = (new DhenService)->scrape(); + + foreach ($articles as $article) { + + // Attach the relationship between source and article and return the curren article instance + $articleModel = $source->articles()->firstOrCreate(["guid" => $article["guid"]], + [ + "title" => $article["title"], + "url" => $article["url"], + "author" => $article["author"], + "featured_image" => $article["image"], + "body" => $article["content"], + "published_date" => $article["date"], + "meta" => [ + "title" => $article["og_title"] + ] + + ]); + + collect($article["topics"])->each(function($topic) use ($articleModel) { + $topicModel = Topic::firstOrCreate(["slug" => $topic["slug"]],["name" => $topic["name"]]); + + $topicModel->articles()->syncWithoutDetaching($articleModel); + }); + + } + } +} diff --git a/app/Services/DhenService.php b/app/Services/DhenService.php new file mode 100644 index 0000000..55329d7 --- /dev/null +++ b/app/Services/DhenService.php @@ -0,0 +1,28 @@ +get("https://dhen.mv/feed")["channel"]["item"]; + + $articlesitems = []; + //Looping through the articles and scraping and while scraping it creates a new instance of the scraper. + foreach ($articles as $article) { + $link = $article['link']; + $articlesitems[] = (new DhenScraper)->extract($link); + } + + return $articlesitems; + } +} diff --git a/app/Services/Scrapers/DhenScraper.php b/app/Services/Scrapers/DhenScraper.php new file mode 100644 index 0000000..36ca2e6 --- /dev/null +++ b/app/Services/Scrapers/DhenScraper.php @@ -0,0 +1,61 @@ +client = new Client; + } + + public function extract($url) + { + + $crawler = $this->client->request('GET', $url); + + $title = $crawler->filter('h1')->first()->text(); + + + + $image = $crawler->filter('article .article-visual img')->first()->attr('src'); + + $crawler->filter('article .article-entry p')->each(function ($node) { + $this->content[] = preg_replace("/[a-zA-Z]/","",$node->text()); + }); + + + + if($crawler->filter(".story-item--meta a")->count() == 1) + { + $this->author = $crawler->filter('.story-item--meta a')->first()->text(); + } + + //Remove all the alphabets from string + //preg_replace("/[a-zA-Z]/", "",$string); + return [ + 'source' => 'Dhen', + 'title' => $title, + 'og_title' => $crawler->filter('meta[property*="og:title"]')->first()->attr('content'), + 'image' => $image, + 'content' => $this->content, + 'url' => $url, + 'date' => Carbon::parse(str_replace("- ", "", $crawler->filter('.story-item--meta time')->first()->text()))->format("Y-m-d H:i:s"), + 'guid' => str_replace("https://dhen.mv/","",$url), + 'author' => $this->author, + 'topics' => [ + [ + "name" => "ވަކި މަޢުލޫއެއް ނޭންގެ", + "slug" => "uncategorized" + ] + ] + ]; + } +} \ No newline at end of file