PHP code example of jez500 / web-scraper-for-laravel
1. Go to this page and download the library: Download jez500/web-scraper-for-laravel library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jez500 / web-scraper-for-laravel example snippets
use Jez500\WebScraperForLaravel\Facades\WebScraper;
$scraper = WebScraper::http()->from('https://example.com')->get();
$title = $scraper->getSelector('title')->first();
use Jez500\WebScraperForLaravel\Facades\WebScraper;
// Get an instance of the scraper with the body of the page loaded
$scraper = WebScraper::http()->from('https://example.com')->get();
// Get the full page body
$body = $scraper->getBody();
// Get the first title element
$title = $scraper->getSelector('title')->first();
// Get the content attribute of the first meta tag with property og:image
$image = $scraper->getSelector('meta[property=og:image]|content')->first();
// Get all paragraph innerHtml as an array
$paragraphs = $scraper->getSelector('p')->all();
// Get all links as an array
$links = $scraper->getSelector('a|href')->all();
// Get the first matching element with a specific class
$price = $scraper->getSelector('.product-price')->first();
// Get the first h1 element
$h1 = $scraper->getXpath('//h1')->first();
// Get the href attribute of the first link
$linkHref = $scraper->getXpath('//a', 'attr', ['href'])->first();
// Get multiple elements with a specific attribute
$images = $scraper->getXpath('//img[@class="product-image"]')->all();
// Complex XPath query
$productTitle = $scraper->getXpath('//div[@class="product"]/h1')->first();
// Get nested JSON data from API response
$author = WebScraper::http()
->from('https://api.example.com/page.json')
->get()
->getJson('user.name')
->first();
// Extract all items from an array
$products = WebScraper::http()
->from('https://api.example.com/products.json')
->get()
->getJson('products.*.name')
->all();
// Extract multiple nested fields
$emails = WebScraper::http()
->from('https://api.example.com/users.json')
->get()
->getJson('users.*.email')
->all();
// Get title from a JavaScript-rendered page
$title = WebScraper::api()
->from('https://example.com')
->get()
->getSelector('title')
->first();
// Extract data from a Single Page Application
$data = WebScraper::api()
->from('https://example.com/app')
->get()
->getSelector('[data-content]')
->first();
// Set a custom user agent
$scraper = WebScraper::http()
->from('https://example.com')
->withUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
->get();