使用 goutte 从文件/字符串中读取

All*_*lly 5 php web-scraping symfony goutte

我正在使用 Goutte 制作网络爬虫。

为了进行开发,我保存了一个我想要遍历的 .html 文档(因此我不会不断向网站发出请求)。这是我到目前为止所拥有的:

use Goutte\Client;

$client = new Client();
$html=file_get_contents('test.html');
$crawler = $client->request(null,null,[],[],[],$html);
Run Code Online (Sandbox Code Playgroud)

据我所知,应该在 Symfony\Component\BrowserKit 中调用请求,并传入原始正文数据。这是我收到的错误消息:

PHP Fatal error:  Uncaught exception 'GuzzleHttp\Exception\ConnectException' with message 'cURL error 7: Failed to connect to localhost port 80: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)' in C:\Users\Ally\Sites\scrape\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.
Run Code Online (Sandbox Code Playgroud)

如果我只使用 DomCrawler,那么使用字符串创建爬虫并不简单。(参见: http: //symfony.com/doc/current/components/dom_crawler.html)。我只是不确定如何用 Goutte 做同样的事情。

提前致谢。

Jak*_*las 6

您决定使用的工具可以建立真正的 http 连接,但不适合您想要做的事情。至少开箱即用。

选项 1:实现您自己的 BrowserKit 客户端

gooutte 所做的只是扩展了 BrowserKit 的Client。它使用 Guzzle 实现 http 请求。

要实现自己的客户端,您所需要做的就是扩展Symfony\Component\BrowserKit\Client并提供doRequest()方法

use Symfony\Component\BrowserKit\Client;
use Symfony\Component\BrowserKit\Request;
use Symfony\Component\BrowserKit\Response;

class FilesystemClient extends Client
{
    /**
     * @param object $request An origin request instance
     *
     * @return object An origin response instance
     */
    protected function doRequest($request)
    {
        $file = $this->getFilePath($request->getUri());

        if (!file_exists($file)) {
            return new Response('Page not found', 404, []);
        }

        $content = file_get_contents($file);

        return new Response($content, 200, []);
    }

    private function getFilePath($uri)
    {
        // convert an uri to a file path to your saved response
        // could be something like this:
        return preg_replace('#[^a-zA-Z_\-\.]#', '_', $uri).'.html';
    }
}
Run Code Online (Sandbox Code Playgroud)
 $client = new FilesystemClient();
 $client->request('GET', '/test');
Run Code Online (Sandbox Code Playgroud)

客户端request()需要接受真实的 URI,因此您需要实现自己的逻辑以将其转换为文件系统位置。

看看Goutte 的 Client以获得灵感。

选项 2:实现自定义 Guzzle 处理程序

由于 Goutte 使用 Guzzle,因此您可以提供自己的 Guzzle 处理程序来加载来自文件的响应,而不是发出真正的 http 请求。查看处理程序和中间件文档

如果您只是想缓存响应以减少 http 请求,Guzzle 已经提供了对此的支持。

选项3:直接使用DomCrawler

new Crawler(file_get_contents('test.html'))
Run Code Online (Sandbox Code Playgroud)

唯一的缺点是您将失去 BrowserKit 客户端的一些便捷方法,例如click()selectLink()