使用R语言RSelenium包的rsDriver函数时遇错误求助
解决RSelenium中free_port()函数的编码错误问题
问题详情
执行RSelenium启动Chrome的代码时出现编码相关错误:
rs_driver_object <- rsDriver(browser="chrome", chromever = "113.0.5672.63", verbose = F, port=free_port())
错误信息:
Error in gsub("\s+", ",", ActiveConnections) : input string 1 is invalid In addition: Warning message: In gsub("\s+", ",", ActiveConnections) : unable to translate ' Proto Adresse locale Adresse distante <90>tat' to a wide string
前置可正常运行代码:
library(tidyverse) library(RSelenium) library(netstat) library(wdman) # 下载chromedriver selenium() # 查看chromedriver安装路径 selenium_object <- selenium (retcommand = T, check = F) # 查看可用chromedriver版本 binman::list_versions("chromedriver")
环境信息:
- Chrome版本:113.0.5672.127
- 可用chromedriver版本:
$win32 "113.0.5672.24" "113.0.5672.63" "114.0.5735.16"
错误根源是free_port()函数读取系统端口信息时,未处理非ASCII字符(比如系统语言为法语时,状态字段"État"显示为乱码),导致gsub字符串处理失败。
解决方案
1. 自定义编码兼容的空闲端口检测函数
重写free_port(),添加编码处理逻辑,适配非ASCII系统语言:
my_free_port <- function(start = 4567L, end = 5000L, n = 1L) { if (.Platform$OS.type == "windows") { # Windows系统下指定UTF-8编码读取端口信息 con <- pipe("netstat -ano", open = "r") lines <- readLines(con, encoding = "UTF-8") close(con) # 提取LISTENING状态的端口 used_ports <- as.integer(gsub("^.*:(\\d+)\\s+.*LISTENING.*$", "\\1", lines[grepl("LISTENING", lines)])) } else { # 类Unix系统逻辑 con <- pipe("lsof -i -P -n | grep LISTEN", open = "r") lines <- readLines(con) close(con) used_ports <- as.integer(gsub("^.*:(\\d+)\\s+.*$", "\\1", lines)) } # 筛选空闲端口 available_ports <- setdiff(start:end, used_ports) if (length(available_ports) < n) { stop("指定范围内无可用空闲端口") } sample(available_ports, n) }
调用时替换为自定义函数:
rs_driver_object <- rsDriver(browser="chrome", chromever = "113.0.5672.63", verbose = F, port=my_free_port())
2. 手动遍历检测空闲端口
从指定起始端口开始,逐个检测是否被占用,找到第一个空闲端口:
# 检测端口是否空闲的函数 is_port_free <- function(port) { if (.Platform$OS.type == "windows") { con <- pipe(paste0("netstat -ano | findstr :", port), open = "r") result <- readLines(con, warn = FALSE) close(con) length(result) == 0 } else { con <- pipe(paste0("lsof -i :", port), open = "r") result <- readLines(con, warn = FALSE) close(con) length(result) == 0 } } # 从4567开始查找空闲端口 port <- 4567 while(!is_port_free(port)) { port <- port + 1 } # 使用该端口启动RSelenium rs_driver_object <- rsDriver(browser="chrome", chromever = "113.0.5672.63", verbose = F, port=port)
3. 切换端口检测函数
尝试使用wdman包自带的free_port()替代netstat包的版本,部分场景下该函数编码处理更完善:
rs_driver_object <- rsDriver(browser="chrome", chromever = "113.0.5672.63", verbose = F, port=wdman::free_port())
内容的提问来源于stack exchange,提问作者Styscience
相关产品推荐
相关产品推荐

