Selenium找到元素,但随机不会点击一个元素,尽管它在firefox上也是如此

时间:2016-12-16 11:29:19

标签: java selenium firefox xpath webdriver

我正在开发一个程序来自动化一些表格填充,我正在使用Selenium。自从开始以来一直困扰我的问题,如果这项工作,是一个应该单击按钮的指令不起作用并且不返回任何错误。这是随机发生的,但是在我第一次运行程序时,它经常发生。

基本上驱动程序必须进入一个站点,用登录填充一个弹出窗口,然后当第一页加载时,必须单击一个按钮,这将打开第二页。会发生的是,如果不打开第二页,驱动程序已经在寻找属于它的元素。

起初我认为浏览器和驱动程序可能不同步,驱动程序比浏览器更快,并且不知何故搞乱了整个过程。我尝试用半秒的睡眠来纠正这个问题。还实现了15秒的隐式等待。

没有任何改进,我决定检查是否找到了第一个元素。我已经插入一行来将按钮上的文本打印到控制台并正确打印。下一行是单击该按钮,虽然驱动程序没有检索到错误,但在浏览器上只加载了第一页。

最后但并非最不重要的是尝试使用该xpath查找所有元素,但列表只有一个元素。

因此,总而言之,找到第一个元素,点击指令不会检错,但仍然没有点击按钮。这是随机发生的。

以下是我正在使用的代码的相关部分:

tester.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
    tester.get(website);
        Thread.sleep(1000);

        //Bypasses login pop-up window
        try
        {
            bypassLogin(username, password);
        }
        catch(Exception e)
        {
            handler(e.getMessage(), null);
            finisher(tester, br, br2, pathGecko, pathTemplate);
        }

        //Sleep in order to synchronize driver and browser
        Thread.sleep(1000);

        while((reader = br2.readLine()) != null)
        {
            tempOrig = new StringBuilder()
                            .append(tempOrig)
                            .append(reader)
                            .toString();
        }

        //Enters the body frame, with the elements to work with
        try
        {
            tester.switchTo().frame("portal_header");
            List <WebElement> LClick = tester.findElements(By.xpath(".//*[@id='2']/a"));
            System.out.println(LClick.size()); //Returns 1
            tester.findElement(By.xpath(".//*[@id='2']/a")).getText(); //Returns the correct value
            tester.findElement(By.xpath(".//*[@id='2']/a")).click();
            tester.switchTo().defaultContent();
            tester.switchTo().frame("portal_body");
        }
        catch(Exception e)
        {
            handler(e.getMessage(), null);
            finisher(tester, br, br2, pathGecko, pathTemplate);
        }

1 个答案:

答案 0 :(得分:0)

试试这个并检查

WebDriverWait wait = new WebDriverWait(tester, 15);
boolean bool = tester.findElement(By.xpath(".//*[@id='2']/a")).isDisplayed();
System.out.print(bool);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='2']/a")));
tester.findElement(By.xpath(".//*[@id='2']/a")).click();

还要检查浏览器版本和selenium版本

相关问题