很多时候,当爬行时,我们会遇到这样的问题:页面上呈现的内容是用 Javascript 生成的,因此 scrapy 无法爬行它(例如 ajax 请求、jQuery)
你想看看 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();
}
}
使用 phantom 的唯一缺点是,它会比 guzzle 慢,但是当然,你必须等待所有那些讨厌的 js 加载完毕。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)