PhantomJS使用太多线程

Dav*_*ong 7 javascript web-crawler phantomjs

我写了一个PhantomJS应用程序来抓取我构建的网站并检查要包含的JavaScript文件.JavaScript类似于Google,其中一些内联代码加载到另一个JS文件中.该应用程序查找其他JS文件,这就是我使用Phantom的原因.

预期的结果是什么?

控制台输出应读取大量URL,然后判断脚本是否已加载.

真的发生了什么?

控制台输出将按预期读取大约50个请求,然后才开始吐出此错误:

2013-02-21T10:01:23 [FATAL] QEventDispatcherUNIXPrivate(): Can not continue without a thread pipe
QEventDispatcherUNIXPrivate(): Unable to create thread pipe: Too many open files
Run Code Online (Sandbox Code Playgroud)

这是打开页面并搜索脚本的代码块包括:

page.open(url, function (status) {
    console.log(YELLOW, url, status, CLEAR);
    var found =  page.evaluate(function () {
      if (document.querySelectorAll("script[src='***']").length) {
        return true;
      } else { return false; }
    });

    if (found) {
      console.log(GREEN, 'JavaScript found on', url, CLEAR);
    } else {
      console.log(RED, 'JavaScript not found on', url, CLEAR);
    }
    self.crawledURLs[url] = true;
    self.crawlURLs(self.getAllLinks(page), depth-1);
  });
Run Code Online (Sandbox Code Playgroud)

crawledURLs对象只是我已经抓取的网址对象.crawlURLs函数只是通过getAllLinks函数的链接,并在具有爬虫启动的域的基本域的所有链接上调用open函数.

编辑

我修改了代码的最后一个块如下,但仍然有相同的问题.我已将page.close()添加到该文件中.

if (!found) {
  console.log(RED, 'JavaScript not found on', url, CLEAR);
}
self.crawledURLs[url] = true;
var links = self.getAllLinks(page);
page.close();
self.crawlURLs(links, depth-1);
Run Code Online (Sandbox Code Playgroud)

Ari*_*yat 6

从文档:

由于某些技术限制,网页对象可能不会完全被垃圾收集.当一遍又一遍地使用相同的对象时经常会遇到这种情况.

解决方案是在适当的时间显式调用close()网页对象(即page在许多情况下).

一些包含的示例(例如follow.js)演示了具有显式关闭的多个页面对象.


Jos*_*ter 5

打开文件限制。

即使正确关闭文件,您仍然可能会遇到此错误。

在搜索互联网后,我发现您需要增加单个进程允许打开的文件数量的限制。就我而言,我生成了数百到数千页的 PDF。

根据您运行的系统,有不同的方法来调整此设置,但以下是在Ubuntu服务器上对我有用的方法

将以下内容添加到 的末尾/etc/security/limits.conf

# Sets the open file maximum here.
# Generating large PDFs hits the default ceiling (1024) quickly. 
*    hard nofile 65535
*    soft nofile 65535
root hard nofile 65535 # Need these two lines because the wildcards (above)
root soft nofile 65535 # are not applied to the root user as well.
Run Code Online (Sandbox Code Playgroud)

可以在此处ulimit找到该命令的良好参考。

我希望这能让一些人走上正确的道路。