Java:Selenium返回脚本超时,而不是找不到元素

如何解决Java:Selenium返回脚本超时,而不是找不到元素

我有一个奇怪的问题。页面和PageObject存在于Selenium正常工作的其他页面和PageObjects之间的情况下,会发生这种情况。但是对于此页面(和PageObject),Selenium没有。

当我尝试访问不在页面上的页面元素时,硒返回几分钟后出现以下错误,而不是返回“找不到元素”:

org.openqa.selenium.TimeoutException: timeout: Timed out receiving message from renderer: 10.000
...
org.openqa.selenium.ScriptTimeoutException: script timeout
(Session info: chrome=84.0.4147.105)
Build info: version: '3.141.59',revision: 'e82be7d358',time: '2018-11-14T08:17:03'
System info: host: 'ubuntu',ip: '127.0.1.1',os.name: 'Linux',os.arch: 'amd64',os.version: 
'5.3.0-7648-generic',java.version: '1.8.0_265'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false,browserName: chrome,browserVersion: 84.0.4147.105,c
chrome: {chromedriverVersion: 84.0.4147.105 (a6b12dfad666...,userDataDir: 
/tmp/.org.chromium.Chromium...},goog:chromeOptions: {debuggerAddress: localhost:36301},javascriptEnabled: true,networkConnectionEnabled: false,pageLoadStrategy: normal,platform: LINUX,platformName: LINUX,proxy: Proxy(),setWindowRect: true,strictFileInteractability: false,timeouts: {implicit: 0,pageLoad: 300000,script: 30000},unhandledPromptBehavior: dismiss and 
notify,webauthn:virtualAuthenticators: true}
Session ID: a87f945bc7eb66a98cec5f0b2416b47a
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
 at 
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
 at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
 at 
org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
 at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
 at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
 at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebDriver.executeAsyncScript(RemoteWebDriver.java:506)
at 
no.husbanken.e2e.rammeverk.selenium.driver.ExtendedWebDriver.isPageReady(ExtendedWebDriver.java:46)
 at 
no.husbanken.e2e.rammeverk.selenium.driver.ExtendedWebDriver.findElement(ExtendedWebDriver.java:65)

我知道超时本身并不是很奇怪,但是当我尝试访问其他页面上不存在的元素时,它们会返回预期的“找不到元素”。

PageObject:

public class VedleggPage2 {
    private ExtendedWebDriver driver;
    private String url;

    @FindBy(css = "[data-e2e-selector=sidetittel]")
    private WebElement sidetittel;
    @FindBy(css = "[data-e2e-selector=vedleggtekst]")
    private WebElement vedleggtekst;

    public VedleggPage2() {
        this.driver = Browser.extendedDriver();
        this.url = ConfigManager.config.getEsoknadWebUrl() + "soknad/";
        PageFactory.initElements(driver,this);
    }

    public void navigerTil() {
        navigerTil(Session.scenarioState.getSoknadId(SOKNAD_1_TAG));

        //For testing purposes:
        List<WebElement> jajaja = driver.findElements(By.cssSelector("sidetittel"));
        Boolean janei = sidetittel.isDisplayed();
        Boolean neija = vedleggtekst.isDisplayed();
        sidetittel.click();
        String s = sidetittel.getText()
        driver.findElement(By.id("sidetittel")).click();
        driver.findElement(By.cssSelector("[data-e2e-selector=sidetittel]")).click();
        driver.findElement(By.cssSelector("[data-e2e-selector=vedleggtekst]")).click();
        driver.findElement(By.id("notexisting")).click();
        driver.findElement(By.id("notexisting")).getText();
        Boolean visible1 = driver.findElement(By.id("sidetittel")).isDisplayed();
        Boolean visible2 = driver.findElement(By.cssSelector("[data-e2e-
          selector=vedleggtekst]")).isDisplayed();
        Boolean visible3 = driver.findElement(By.cssSelector("[data-e2e-
          selector=vedleggtekst]")).isDisplayed();
        Boolean visible4 = driver.findElement(By.id("notexisting")).isDisplayed();
        
    }
}

所有尝试访问“ //出于测试目的”行下现有和不存在的元素的尝试都会导致上面的长时间超时和脚本超时错误,而不是“找不到元素”。而且,某些元素肯定存在,并且不应导致任何错误。 (非常基本的)PageObject代码中没有任何东西会导致此行为。

我什至尝试将问题行放置在其他PageObjects中,并且它们在那里的行为完全相同。当那些其他PageObjects用于访问其各自的页面时,它们将按预期工作。所以现在看来​​,这种情况发生在该特定网页上。

有什么想法吗?

更新:更多故障排除显示,如果我导航到同一站点/应用程序中的另一个页面,则它的工作原理就像一个超级按钮。因此,超时问题出在特定页面上(还有其他页面,因为我怀疑只有这样一个页面)。

UPDATE2:驱动程序初始化和isPageReady()方法位于与应用程序代码分离的框架中。我认为这是相关的代码:

ExtendedWebDriver.java:

public ExtendedWebDriver(final WebDriver webDriver,final String 
venteScript) {
    if (!(webDriver instanceof JavascriptExecutor)) {
        throw new WebDriverException("The WebDriver instance must implement 
        JavaScriptExecutor interface.");
    }
    if (venteScript == null || venteScript.isEmpty()) {
        throw new WebDriverException("Ingen ventescript spesifisert");
    }
    this.webDriver = webDriver;
    this.jsExecutor = (JavascriptExecutor) webDriver;
    this.venteScript = venteScript;
}

public JavascriptExecutor getJsExecutor() {
    return jsExecutor;
}

public void isPageReady() {
    Object response = jsExecutor.executeAsyncScript(venteScript);
    if (response != null) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        response = jsExecutor.executeAsyncScript(venteScript);
        if(response!=null) {
            throw new IllegalStateException(format("Responsen fra 
             isPageReady() skal alltid være null,men var: %s",response));
        }
    }
}

WebDriverFactory.java:

public class WebDriverFactory {

    public static ExtendedWebDriver getExtendedWebDriver(WebDriver driver,SeleniumOptions.WebAppTeknologi teknologi) {
        return new ExtendedWebDriver(driver,JsUtils.getScript(teknologi));
    }
}

JsUtils.java:

public class JsUtils {
    private static final HashMap<SeleniumOptions.WebAppTeknologi,String> scripts;

    static {
        scripts = new HashMap<>();
        initScripts();
    }

    private static void initScripts() {
        scripts.put(SeleniumOptions.WebAppTeknologi.ANGULAR,getAngularScript());
        scripts.put(SeleniumOptions.WebAppTeknologi.PRIMEFACES,getPrimefacesScript());
    }

    private static String getAngularScript() {
        return "function getNg1Hooks(t,e){function n(t){try{if(!e&&angular.getTestability){var n=angular.getTestability(t);if" +
            "(n)return{$$testability:n}}else{var i=angular.element(t).injector();if(i)return{$injector:i}}}catch(t)" +
            "{}}function i(t){for(var e=document.querySelectorAll(t),i=0;i<e.length;i++){var r=n(e[i]);if(r)return r}}if(t)" +
            "return i(t);if(window.__TESTABILITY__NG1_APP_ROOT_INJECTOR__){var r=window" +
            ".__TESTABILITY__NG1_APP_ROOT_INJECTOR__,a=null;try{a=r.get(\"$$testability\")}catch(t){}return{$injector:r," +
            "$$testability:a}}return n(document.body)||i(\"[ng-app]\")||i(\"[ng\\\\:app]\")||i(\"[ng-controller]\")||i" +
            "(\"[ng\\\\:controller]\")}waitForAngular=function(t,e){try{var n=e;if(!window.angular&&!window" +
            ".getAngularTestability)throw new Error(\"both angularJS testability and angular testability are undefined.  " +
            "This could be either because this is a non-angular page or because your test involves client-side navigation," +
            "which can interfere with Protractor's bootstrapping.  See http://git.io/v4gXM for details\");!function(e){if" +
            "(window.angular){var n=getNg1Hooks(t);if(n)if(n.$$testability)n.$$testability.whenStable(e);else{if(!n" +
            ".$injector)throw t?new Error(\"root element (\"+t+\") has no injector. this may mean it is not inside ng-app" +
            ".\"):new Error('Could not automatically find injector on page: \"'+window.location.toString()+'\".  Consider " +
            "using config.rootEl');n.$injector.get(\"$browser\").notifyWhenNoOutstandingRequests(e)}else e()}else e()}" +
            "(function(){if(window.getAngularTestability){if(t){var e=null,i=document.querySelector(t);try{e=window" +
            ".getAngularTestability(i)}catch(t){}if(e)return void e.whenStable(n)}var r=window.getAllAngularTestabilities()" +
            ",a=r.length;if(0===a)return void n();var o=function(){0==--a&&n()};r.forEach(function(t){t.whenStable(o)})" +
            "}else n()})}catch(t){e(t.message)}},waitForAngular(\"body\",arguments[arguments.length-1]);";
    }

    private static String getPrimefacesScript() {
        return "waitForPrimefaces=function(e){try{if(!window.jQuery)throw window.jQuery?new Error(\"Unknown Error\"):new Error" +
            "(\"window.jQuery is undefined.  This could be either because this is a non-jquery page or because your test " +
            "involves client-side navigation\");if(WaitForAjax(),void 0===window.PrimeFaces)throw new Error(\"typeof " +
            "PrimeFaces  is undefined.  This could be either because this is a non-primefaces page or because your test " +
            "involves client-side navigation\");WaitForPF(),e(null)}catch(i){e(i.message)}};var WaitForAjax=function()" +
            "{0!==window.jQuery.active&&setTimeout(WaitForAjax,50)},WaitForPF=function(){window.PrimeFaces.ajax.Queue" +
            ".isEmpty()||setTimeout(WaitForPF,50)};waitForPrimefaces(arguments[arguments.length-1]);";
    }

    public static String getScript(SeleniumOptions.WebAppTeknologi key) {
        return scripts.get(key);
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-