Selenium定位元素报错window.crypto.getRandomValues is not a function求助
问题描述
我的Selenium代码在其他应用上运行正常,但在某特定应用中执行时,浏览器能成功启动并打开应用,却在定位元素阶段抛出以下错误:
org.openqa.selenium.JavascriptException: javascript error: window.crypto.getRandomValues is not a function
控制台完整输出:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Starting ChromeDriver 106.0.5249.61 (511755355844955cd3e264779baf0dd38212a4d0-refs/branch-heads/5249@{#569}) on port 51705 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully. Oct 25, 2022 5:18:16 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected upstream dialect: W3C Oct 25, 2022 5:18:16 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch INFO: Found exact CDP implementation for version 106 Application launched successfully Exception in thread "main" org.openqa.selenium.JavascriptException: javascript error: window.crypto.getRandomValues is not a function (Session info: chrome=106.0.5249.119) Build info: version: '4.5.0', revision: 'fe167b119a' System info: os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '16.0.1' Driver info: org.openqa.selenium.chrome.ChromeDriver Command: [d2f82fd9eda093fbeb1872f16a7eca77, findElement {using=xpath, value=//button[@id='signIn_En']}] Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 106.0.5249.119, chrome: {chromedriverVersion: 106.0.5249.61 (511755355844..., userDataDir: C:\Users\Soumya.B\AppData\L...}, goog:chromeOptions: {debuggerAddress: localhost:65297}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: WINDOWS, proxy: Proxy(), se:cdp: ws://localhost:65297/devtoo..., se:cdpVersion: 106.0.5249.119, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true} Session ID: d2f82fd9eda093fbeb1872f16a7eca77 at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:200) at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:133) at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:53) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:184) at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:167) at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:142) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:547) at org.openqa.selenium.remote.ElementLocation$ElementFinder$2.findElement(ElementLocation.java:162) at org.openqa.selenium.remote.ElementLocation.findElement(ElementLocation.java:60) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:365) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:357) at sample.Sample1.main(Sample1.java:23)
解决方案
这个错误是因为目标页面的window.crypto.getRandomValues方法被篡改或未正确加载,导致Selenium执行元素定位时依赖的JS逻辑失效。可以通过以下几种方式解决:
- 页面加载后注入补全方法:在打开页面后、定位元素前,执行JS代码补全该方法。示例代码:
// 打开目标页面后执行 ((JavascriptExecutor) driver).executeScript(""" if (!window.crypto) { window.crypto = {}; } if (!window.crypto.getRandomValues) { window.crypto.getRandomValues = function(array) { for (let i = 0; i < array.length; i++) { array[i] = Math.floor(Math.random() * 256); } return array; }; } """); // 之后再执行元素定位 driver.findElement(By.xpath("//button[@id='signIn_En']"));
- 修改Chrome启动参数:添加
--disable-blink-features=AutomationControlled参数,绕过页面的自动化检测,避免页面篡改window.crypto相关属性。示例代码:
ChromeOptions options = new ChromeOptions(); options.addArguments("--disable-blink-features=AutomationControlled"); WebDriver driver = new ChromeDriver(options);
- 等待页面完全加载:确保页面所有资源(包括JS脚本)加载完成后再定位元素,可以使用显式等待:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//button[@id='signIn_En']")));
内容的提问来源于stack exchange,提问作者Sowmya Bitla
相关产品推荐
相关产品推荐

