phplaravelweb-scrapingguzzlegoutte

Call to undefined method Goutte\Client::setClient()


I am stuck with this error... but the client is defined.

my code like this

use Goutte\Client;
use Illuminate\Http\Request;
use GuzzleHttp\Client as GuzzleClient;

class WebScrapingController extends Controller
{
    public function doWebScraping() 
    {
        $goutteClient = new Client();
        $guzzleClient = new GuzzleClient(array(
            'timeout' => 60,
            'verify' => false
        ));
        $goutteClient->setClient($guzzleClient);
        $crawler = $goutteClient->request('GET', 'https://duckduckgo.com/html/?q=Laravel');
        $crawler->filter('.result__title .result__a')->each(function ($node) {
            dump($node->text());
        });
    }
}

I think error from this line

$goutteClient->setClient($guzzleClient);

goutte: "^4.0"
guzzle: "7.0"
Laravel Framework: "6.20.4"



Solution

  • This answer is regarding creating instance of Goutte client, a simple PHP Web Scraper


    For Version >= 4.0.0

    Pass HttpClient(either guzzle httpclient , symfony httpclient) instance directly inside the instance of Goutte Client.

    use Goutte\Client;
    use Symfony\Component\HttpClient\HttpClient;// or use GuzzleHttp\Client as GuzzleClient;
    
    $client = new Client(HttpClient::create(['timeout' => 60]));
    // or 
    // $guzzleClient = new GuzzleClient(['timeout' => 60, 'verify' => false]); // pass this to Goutte Client
    

    For Version <= 4.0.0 (i.e from 0.1.0 to 3.3.1)

    use Goutte\Client;
    use GuzzleHttp\Client as GuzzleClient;
    
    $goutteClient = new Client();
    $guzzleClient = new GuzzleClient(['timeout' => 60]);
    $goutteClient->setClient($guzzleClient);