Selenium Grid启用Basic Auth后测试无法交互元素(EKS环境)
Selenium Grid启用Basic Auth后测试无法与页面元素交互
我在EKS环境部署了v0.20.1版本的Selenium Grid,启用Basic Auth后,测试无法和页面元素交互,抛出以下错误:
Unable to parse: <html> <head><title>403 Forbidden</title></head> <body> <center><h1>403 Forbidden</h1></center> </body> </html> org.openqa.selenium.json.JsonException: Unable to determine type from: <. Last 1 characters read: < Build info: version: '4.11.0', revision: '040bc5406b' System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '13.5', java.version: '17.0.6' Driver info: driver.version: RemoteWebDriver
问题原因
这个403错误是因为RemoteWebDriver向Selenium Grid发起请求时,没有携带Basic Auth认证凭证,被Grid的权限拦截,导致无法建立正常通信,进而无法操作页面元素。
解决办法
直接在Grid URL中嵌入认证信息
初始化RemoteWebDriver时,使用包含用户名和密码的URL格式:String gridUrl = "http://your-username:your-password@your-grid-host:4444/wd/hub"; RemoteWebDriver driver = new RemoteWebDriver(new URL(gridUrl), new ChromeOptions());通过请求拦截器添加Authorization头(Selenium 4+适用)
若不想在URL中暴露凭证,可手动添加认证头:import org.openqa.selenium.remote.HttpCommandExecutor; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.codec.w3c.W3CHttpCommandCodec; import org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Base64; public class GridAuthExample { public static void main(String[] args) { String gridEndpoint = "http://your-grid-host:4444/wd/hub"; String username = "your-username"; String password = "your-password"; // 生成Basic Auth凭证 String authCredentials = username + ":" + password; String encodedAuth = Base64.getEncoder().encodeToString(authCredentials.getBytes(StandardCharsets.UTF_8)); String authHeader = "Basic " + encodedAuth; // 创建带拦截器的命令执行器 HttpCommandExecutor executor = new HttpCommandExecutor(URI.create(gridEndpoint)); executor.setCommandCodec(new W3CHttpCommandCodec()); executor.setResponseCodec(new W3CHttpResponseCodec()); // 注入Authorization头 executor.addInterceptor((request, response) -> request.addHeader("Authorization", authHeader)); // 初始化Driver RemoteWebDriver driver = new RemoteWebDriver(executor, new ChromeOptions()); // 后续测试逻辑... } }验证Grid配置
确认helm values.yaml中配置的Basic Auth用户名和密码,与测试代码中使用的完全一致,避免因凭证不匹配导致拦截。
内容的提问来源于stack exchange,提问作者deepakguna
相关产品推荐
相关产品推荐

