selenium+phantomjs報錯:Unable to find a free port的分析和解決
1 現象
在做項目時,發現在某台機器上使用selenium+phantomjs時報如下錯誤:
java.lang.RuntimeException: Unable to find a free port at org.openqa.selenium.net.PortProber.findFreePort(PortProber.java:67) at org.openqa.selenium.phantomjs.PhantomJSDriverService$Builder.build(PhantomJSDriverService.java:443) ...
2 分析
通過跟蹤源代碼(org.openqa.selenium.net.PortProber.createAcceptablePort),發現:
if (FIRST_PORT == LAST_PORT) { return FIRST_PORT; }
在該服務器上,FIRSTPORT = LASTPORT = 1024,因此總是返回1024。
查看服務器的可用本地端口配置,如下:
[gyx@interface01 ~]$ cat /proc/sys/net/ipv4/ip_local_port_range 1024 65535
因為這台機器的最低可用端口配置成了1024,而其他機器都比這個大很多,因此造成了上述問題。
3 解決辦法
因為該服務器還有別的用處,不能隨意修改可用端口配置,所以,暫時通過修改createAcceptablePort中相應代碼解決問題。如下:
if (FIRST_PORT == LAST_PORT) { // return FIRST_PORT; final int randomInt = random.nextInt(); System.out.println("randomInt = " + randomInt); final int portWithoutOffset = Math.abs(randomInt % (HIGHEST_PORT - START_OF_USER_PORTS + 1)); return portWithoutOffset + FIRST_PORT; }