【问题标题】:How to scrape in laravel 5.2 using Goutte?如何使用 Goutte 在 laravel 5.2 中刮擦?
【发布时间】:2016-06-02 17:32:11
【问题描述】:

我是 Laravel 5.2 的新手,我想抓取一个网页。我知道可以使用Goutte 来完成。而且不知道怎么用。

我已经安装了 Laravel 和 Goutte,但是如何使用呢?如何设置Controller、路由和所有需要的东西?

【问题讨论】:

  • 我刚刚安装了库文件
  • 您想在 Web 应用程序中使用 Goutte 吗?这是可能的,尽管我通常在 Web 服务器外部的控制台程序中执行此操作(因为抓取是一项缓慢的活动,并且您不想阻止您的 Web 服务器)。一个好的第一种方法是创建一个快速的控制台程序来执行你想做的抓取,并让它在那里工作(即完全没有 Laravel)。你可以用大约 10 行代码在 Goutte 中进行基本的抓取。
  • 您是否尝试过 repo README 中的 Goutte 示例?

标签: php web-scraping laravel-5.2 goutte


【解决方案1】:

我找到了答案。 我只是将 url 添加到路由并创建了控制器

Route::resource('scrape','WebScraperController@index');

WebScraperController 内部

<?php

  namespace App\Http\Controllers;

  use Illuminate\Http\Request;
  use Goutte\Client;
  use Symfony\Component\DomCrawler\Crawler;
  use App\Http\Requests;
  class WebScraperController extends Controller
  {
  public function index()
  {
  //  Create a new Goutte client instance
    $client = new Client();

 //  Hackery to allow HTTPS
    $guzzleclient = new \GuzzleHttp\Client([
        'timeout' => 60,
        'verify' => false,
    ]);

    // Create DOM from URL or file
    $html = file_get_html('https://www.facebook.com');

    // Find all images
    foreach ($html->find('img') as $element) {
        echo $element->src . '<br>';
    }

    // Find all links
    foreach ($html->find('a') as $element) {
        echo $element->href . '<br>';
    }
  }
}

【讨论】:

  • 调用未定义函数 Vanguard\Http\Controllers\web\file_get_html()
猜你喜欢
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 2021-04-13
  • 2020-01-09
  • 2021-09-06
相关资源
最近更新 更多