java - 打开的文件太多(Selenium + PhantomJSDriver)

标签 java scala selenium selenium-webdriver phantomjs

在我的嵌入式 Selenium/PhantomJSDriver 驱动程序中,资源似乎没有被清理。同步运行客户端会导致打开数百万个文件,并最终引发“打开的文件太多”类型的异常。

这是我在程序运行约 1 分钟时从 lsof 收集的一些输出

$ lsof | awk '{ print $2; }' | uniq -c | sort -rn | head
    1221966 12180
      34790 29773
      31260 12138
      20955 8414
      17940 10343
      16665 32332
       9512 27713
       7275 19226
       5496 7153
       5040 14065

$ lsof -p 12180 | awk '{ print $2; }' | uniq -c | sort -rn | head
    2859 12180
       1 PID

$ lsof -p 12180 -Fn | sort -rn | uniq -c | sort -rn | head
    1124 npipe
     536 nanon_inode
       4 nsocket
       3 n/opt/jdk/jdk1.8.0_60/jre/lib/jce.jar
       3 n/opt/jdk/jdk1.8.0_60/jre/lib/charsets.jar
       3 n/dev/urandom
       3 n/dev/random
       3 n/dev/pts/20
       2 n/usr/share/sbt-launcher-packaging/bin/sbt-launch.jar
       2 n/usr/share/java/jayatana.jar

我不明白为什么在 lsof 上使用 -p 标志会产生较小的结果集。但似乎大多数条目都是 pipeanon_inode

客户端非常简单,约 100 行,在使用结束时调用 driver.close()driver.quit()。我尝试了缓存和重用客户端,但它并没有减少打开的文件

case class HeadlessClient(
                           country: String,
                           userAgent: String,
                           inheritSessionId: Option[Int] = None
                         ) {
  protected var numberOfRequests: Int = 0
  protected val proxySessionId: Int = inheritSessionId.getOrElse(new Random().nextInt(Integer.MAX_VALUE))
  protected val address = InetAddress.getByName("proxy.domain.com")
  protected val host = address.getHostAddress
  protected val login: String = HeadlessClient.username + proxySessionId
  protected val windowSize = new org.openqa.selenium.Dimension(375, 667)

  protected val (mobProxy, seleniumProxy) = {

    val proxy = new BrowserMobProxyServer()
    proxy.setTrustAllServers(true)
    proxy.setChainedProxy(new InetSocketAddress(host, HeadlessClient.port))
    proxy.chainedProxyAuthorization(login, HeadlessClient.password, AuthType.BASIC)
    proxy.addLastHttpFilterFactory(new HttpFiltersSourceAdapter() {
      override def filterRequest(originalRequest: HttpRequest): HttpFilters = {
        new HttpFiltersAdapter(originalRequest) {
          override def proxyToServerRequest(httpObject: HttpObject): io.netty.handler.codec.http.HttpResponse = {
            httpObject match {
              case req: HttpRequest => req.headers().remove(HttpHeaders.Names.VIA)
              case _ =>
            }
            null
          }
        }
      }
    })
    proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT)
    proxy.start(0)
    val seleniumProxy = ClientUtil.createSeleniumProxy(proxy)
    (proxy, seleniumProxy)
  }

  protected val driver: PhantomJSDriver = {
    val capabilities: DesiredCapabilities = DesiredCapabilities.chrome()
    val cliArgsCap = new util.ArrayList[String]
    cliArgsCap.add("--webdriver-loglevel=NONE")
    cliArgsCap.add("--ignore-ssl-errors=yes")
    cliArgsCap.add("--load-images=no")

    capabilities.setCapability(CapabilityType.PROXY, seleniumProxy)
    capabilities.setCapability("phantomjs.page.customHeaders.Referer", "")
    capabilities.setCapability("phantomjs.page.settings.userAgent", userAgent)
    capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap)

    new PhantomJSDriver(capabilities)
  }

  driver.executePhantomJS(
    """
      |var navigation = [];
      |
      |this.onNavigationRequested = function(url, type, willNavigate, main) {
      |  navigation.push(url)
      |  console.log('Trying to navigate to: ' + url);
      |}
      |
      |this.onResourceRequested = function(request, net) {
      |    console.log("Requesting " + request.url);
      |    if (! (navigation.indexOf(request.url) > -1)) {
      |        console.log("Aborting " + request.url)
      |        net.abort();
      |    }
      |};
    """.stripMargin
  )

  driver.manage().window().setSize(windowSize)

  def follow(url: String)(implicit ec: ExecutionContext): List[HarEntry] = {
    try{
      Await.result(Future{
        mobProxy.newHar(url)
        driver.get(url)
        val entries = mobProxy.getHar.getLog.getEntries.asScala.toList
        shutdown()
        entries
      }, 45.seconds)
    } catch {
      case e: Exception =>
        try {
          shutdown()
        } catch {
          case shutdown: Exception =>
            throw new Exception(s"Error ${shutdown.getMessage} cleaning up after Exception: ${e.getMessage}")
        }

        throw e
    }
  }

  def shutdown() = {
    driver.close()
    driver.quit()
  }
}

我尝试了多个版本的 Selenium 以防出现错误修复。 build.sbt:

libraryDependencies += "org.seleniumhq.selenium" % "selenium-java"   % "3.0.1"
libraryDependencies += "net.lightbody.bmp" % "browsermob-core" % "2.1.2"           

此外,我尝试了 PhantomJS 2.0.1 和 2.1.1:

$ phantomjs --version
  2.0.1-development

$ phantomjs --version
  2.1.1

这是 PhantomJS 还是 Selenium 的问题?我的客户是否不正确地使用了 API?

最佳答案

资源占用是由BrowserMob引起的。要关闭代理并清理其资源,必须调用 stop()

对于这个客户端,这意味着修改shutdown 方法

def shutdown() = {
  mobProxy.stop()
  driver.close()
  driver.quit()
}

另一种方法,abort,提供了代理服务器的立即终止并且不等待流量停止。

关于java - 打开的文件太多(Selenium + PhantomJSDriver),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41428743/

相关文章:

java - 为什么我在webDriver中找不到 'Function'函数?

java - 将我的 Java 开发从 Windows 切换到 Mac 时,我应该注意什么问题或好处吗?

java - Cassandra:单节点集群中没有足够的副本错误

scala - apache Spark聚合函数使用最小值

scala - 使用预期类型的​​子参数实现 trait 方法

javascript - 在 div 中上下滚动

java - 无法在 ItemStreamReader open 方法中 Autowiring 对象

java - if语句只检查一次

scala - Play Framework 2 : test a request with a json string as body

c# - 在 Selenium C# 中选择单选按钮