Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在控制器中使用爬虫_Php_Unit Testing_Testing_Symfony - Fatal编程技术网

Php 在控制器中使用爬虫

Php 在控制器中使用爬虫,php,unit-testing,testing,symfony,Php,Unit Testing,Testing,Symfony,这在我的测试中正常工作,但我想在控制器中也使用这个爬虫。我怎么做 我创建路线,并添加到控制器: // src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php namespace Acme\DemoBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DemoControllerTest extends WebTest

这在我的测试中正常工作,但我想在控制器中也使用这个爬虫。我怎么做

我创建路线,并添加到控制器:

// src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php
namespace Acme\DemoBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DemoControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/demo/hello/Fabien');

        $this->assertGreaterThan(0, $crawler->filter('html:contains("Hello Fabien")')->count());
    }
}

您不应该在
prod
环境中使用
WebTestCase
,因为
WebTestCase::createClient()
创建测试客户端

在控制器中,您应该执行以下操作(我建议您使用
Buzz\Browser
):


WebTestCase类是一个特殊的类,设计用于在测试框架(PHPUnit)中运行,您不能在控制器中使用它

但您可以创建一个HTTPKernel客户端,如下所示:

use Symfony\Component\DomCrawler\Crawler;
use Buzz\Browser;

...
$browser = new Browser();
$crawler = new Crawler();

$response = $browser->get('/category/index');
$content = $response->getContent();
$crawler->addContent($content);
请注意,您将只能使用此客户端浏览您自己的symfony应用程序。如果你想浏览一个外部服务器,你需要使用另一个客户端,比如goutte

此处创建的爬虫程序与WebTestCase返回的爬虫程序相同,因此您可以遵循symfony中详述的相同示例


如果您需要更多信息,请参阅爬虫组件的文档和类参考

谢谢,+1。此浏览器的文档在哪里?如何获取DOM html等?谢谢,但文档在哪里?如何使用类获取例如DIV或span?
Fatal error: Class 'PHPUnit_Framework_TestCase' not found in /acme/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php on line 24
use Symfony\Component\DomCrawler\Crawler;
use Buzz\Browser;

...
$browser = new Browser();
$crawler = new Crawler();

$response = $browser->get('/category/index');
$content = $response->getContent();
$crawler->addContent($content);
use Symfony\Component\HttpKernel\Client;

...

public function testAction()
{
    $client = new Client($this->get('kernel'));
    $crawler = $client->request('GET', '/category/index');
}