如果数据是通过Javascript加载的,如何使用php Goutte和Guzzle进行爬网?

Bat*_*man 7 php web-crawler scraper goutte guzzle

很多时候,当我们遇到问题时,我们会遇到使用Javascript生成页面上呈现的内容的问题,因此scrapy无法为其抓取(例如,ajax请求,jQuery)

Ale*_*eno 7

你想看看phantomjs.有这个PHP实现:

http://jonnnnyw.github.io/php-phantomjs/

如果你需要让它与PHP一起工作当然.

你可以阅读页面,然后将内容提供给Guzzle,以便使用Guzzle给你的好功能(比如搜索内容等等).这取决于你的需求,也许你可以简单地使用dom,如下所示:

如何按类名获取元素?

这是一些工作代码.

  $content = $this->getHeadlessReponse($url);
  $this->crawler->addContent($this->getHeadlessReponse($url));

  /**
   * Get response using a headless browser (phantom in this case).
   *
   * @param $url
   *   URL to fetch headless
   *
   * @return string
   *   Response.
   */
public function getHeadlessReponse($url) {
    // Fetch with phamtomjs
    $phantomClient = PhantomClient::getInstance();
    // and feed into the crawler.
    $request = $phantomClient->getMessageFactory()->createRequest($url, 'GET');

    /**
     * @see JonnyW\PhantomJs\Http\Response
     **/
    $response = $phantomClient->getMessageFactory()->createResponse();

    // Send the request
    $phantomClient->send($request, $response);

    if($response->getStatus() === 200) {
        // Dump the requested page content
        return $response->getContent();
    }

}
Run Code Online (Sandbox Code Playgroud)

使用幻像的唯一缺点是它会比guzzle慢​​,但当然,你必须等待所有那些讨厌的js加载.


Sha*_*ley 3

Guzzle(Goutte 内部使用)是一个 HTTP 客户端。因此,javascript 内容将不会被解析或执行。驻留在所请求端点之外的 Javascript 文件将不会被下载。

根据您的环境,我认为可以利用PHPv8(嵌入 Google V8 javascript 引擎的 PHP 扩展)和自定义处理程序/中间件来执行您想要的操作。

不过,根据您的环境,使用 JavaScript 客户端执行抓取可能会更容易。