在Selenium WebDriver中,for循环不起作用

时间:2018-05-07 12:46:27

标签: java selenium-webdriver

我在这个页面上要求分析16个不同的行,这些行是自动生成的。我想在每一行中插入分数。如果我只在1行下运行代码(即没有for循环),它工作正常。但是当我运行它超过1行时,它根本不起作用。

在代码中,在for循环中,第一个cssSelector用于按钮。通过点击它将要求两个测试的分数,然后使用保存按钮。

我使用for循环的变量i和第一个cssSelector来改变行。

主要代码:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
* @author KARAN
* MYRACECONTROL
*/
public class mrc {
/**
* @param args
* @throws InterruptedException 
*/
public static void main(String[] args) throws InterruptedException {
int max = 100;
int min = 0;
int rndm = 0;
String rdm;
WebElement edit_button;

System.out.flush();

//Create firefoxDriver Object.
System.setProperty("webdriver.gecko.driver", "C:\\eclipse\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
WebDriverWait w = new WebDriverWait(driver, 10);

// LOGIN 
driver.get("http://ec2####-west-2.compute.amazonaws.com/login");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[2]/div/form/div[2]/div/input")).sendKeys("admin@admin.com");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[2]/div/form/div[3]/div/input")).sendKeys("admin");
edit_button = w.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[3]/div[1]/div[2]/div/form/button[1]")));
edit_button.click();

// JUDGEPANEL
// Navigate to judge panel
driver.navigate().to("http://ec2####-west-2.compute.amazonaws.com/judgepanel");

// select event
Select drpdwn = new Select(driver.findElement(By.id("selector")));
drpdwn.selectByValue("70");
driver.findElement(By.xpath("/html/body/div[3]/div[2]/div[2]/div[1]/div/div[4]/div[2]/button")).click();

// enter scores
for (int i=1; i<=16; i++) {
//edit_button = w.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#entranceList > div:nth-child("+(i+1)+") > div:nth-child(1) > div:nth-child(1) > div:nth-child(4) > button:nth-child(1)")));
//edit_button.click();

driver.findElement(By.cssSelector("#entranceList > div:nth-child("+(i+1)+") > div:nth-child(1) > div:nth-child(1) > div:nth-child(4) > button:nth-child(1)")).click();
System.out.println("Button "+ (i+1) +" Pressed");
rndm = (int)(Math.random()*((max-min)+1));
System.out.println(rndm);
rdm = String.valueOf(rndm);
System.out.println(rdm);
driver.findElement(By.xpath("//*[@id=\"modalSlideUp\"]/div/div/div/div[2]/div/div[1]/input")).sendKeys(rdm);
rndm = (int)(Math.random()*((max-min)+1));
System.out.println(rndm);
rdm = String.valueOf(rndm);
System.out.println(rdm);
driver.findElement(By.xpath("//*[@id=\"modalSlideUp\"]/div/div/div/div[2]/div/div[2]/input")).sendKeys(rdm);
driver.findElement(By.xpath("//*[@id=\"modalSlideUp\"]/div/div/div/div[2]/div/div[3]/button")).click();
System.out.println("Save Button "+ (i+1) +" Pressed");
Thread.sleep(10);
}
}
}

错误:

1525848260543   geckodriver INFO    geckodriver 0.20.1
1525848260563   geckodriver INFO    Listening on 127.0.0.1:4627
1525848261468   mozrunner::runner   INFO    Running command: "C:\\Program Files\\Firefox Developer Edition\\firefox.exe" "-marionette" "-profile" "C:\\Users\\karan\\AppData\\Local\\Temp\\rust_mozprofile.r5X2ICjOSWCR"
Unable to read VR Path Registry from C:\Users\karan\AppData\Local\openvr\openvrpaths.vrpath
Unable to read VR Path Registry from C:\Users\karan\AppData\Local\openvr\openvrpaths.vrpath
Unable to read VR Path Registry from C:\Users\karan\AppData\Local\openvr\openvrpaths.vrpath
Unable to read VR Path Registry from C:\Users\karan\AppData\Local\openvr\openvrpaths.vrpath
Unable to read VR Path Registry from C:\Users\karan\AppData\Local\openvr\openvrpaths.vrpath
1525848268080   Marionette  INFO    Listening on port 50000
1525848268827   Marionette  WARN    TLS certificate errors will be ignored for this session
May 09, 2018 12:14:29 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
JavaScript warning: http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js, line 1: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead
JavaScript warning: http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js, line 1: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: #entranceList > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(4) > button:nth-child(1)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:33:08.638Z'
System info: host: 'KARAN-VAIO', ip: '192.168.1.8', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '10'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities {acceptInsecureCerts: true, browserName: firefox, browserVersion: 61.0, javascriptEnabled: true, moz:accessibilityChecks: false, moz:headless: false, moz:processID: 6740, moz:profile: C:\Users\karan\AppData\Loca..., moz:useNonSpecCompliantPointerOrigin: false, moz:webdriverClick: true, pageLoadStrategy: normal, platform: XP, platformName: XP, platformVersion: 10.0, rotatable: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}}
Session ID: 843fa034-f2ad-40ea-a73c-b43a3f9cfebd
*** Element info: {Using=css selector, value=#entranceList > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(4) > button:nth-child(1)}
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.base/java.lang.reflect.Constructor.newInstance(Unknown Source)
    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:545)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:319)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:413)
    at org.openqa.selenium.By$ByCssSelector.findElement(By.java:430)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:311)
    at mrc.main(mrc.java:71)

示例HTML代码:

<!-- 1st ROW -->
<div ng-if="!isLocked &amp;&amp; !Userlock" class="row ng-scope" ng-repeat="entrance in entranceList">
    <div class="col-xs-12 col-sm-12">
        <div class="row">
            <div class="col-xs-12 col-sm-3 ng-binding">
                Roma G
            </div>
            <div class="col-xs-12 col-sm-3">
                <!--      run1 <input type="number" placeholder="Run 1 score" ng-model=entrance.run1> -->
                run1 <b><span ng-bind="entrance.run1" class="ng-binding"></span></b>
            </div>
            <div class="col-xs-12 col-sm-3">
                <!--     run2 <input type="number" placeholder="Run 2 score" ng-model=entrance.run2> -->
                run2 <b><span ng-bind="entrance.run2" class="ng-binding"></span></b>
            </div>
            <div class="col-xs-12 col-sm-3">
                <!--     <button class="button" ng-click=saveEntraceScore(entrance)> Save</button> -->
                <button id="disablerun" class="btn btn-primary" ng-click="EditEntraceScore(entrance)"> Edit
                <!-- <div ng-if="isbattleTree === true" class="">
                <i class="fa fa-lock"></i>
                </div> -->
                </button>
            </div>
        </div>
        <hr>
        <div class="col-xs-12 col-sm-6">
        </div>
    </div>
</div>

<!-- 2nd ROW -->
<div ng-if="!isLocked &amp;&amp; !Userlock" class="row ng-scope" ng-repeat="entrance in entranceList">
    <div class="col-xs-12 col-sm-12">
        <div class="row">
            <div class="col-xs-12 col-sm-3 ng-binding">
                Jenna M
            </div>
            <div class="col-xs-12 col-sm-3">
                <!--      run1 <input type="number" placeholder="Run 1 score" ng-model=entrance.run1> -->
                run1 <b><span ng-bind="entrance.run1" class="ng-binding"></span></b>
            </div>
            <div class="col-xs-12 col-sm-3">
                <!--     run2 <input type="number" placeholder="Run 2 score" ng-model=entrance.run2> -->
                run2 <b><span ng-bind="entrance.run2" class="ng-binding"></span></b>
            </div>
            <div class="col-xs-12 col-sm-3">
                <!--     <button class="button" ng-click=saveEntraceScore(entrance)> Save</button> -->
                <button id="disablerun" class="btn btn-primary" ng-click="EditEntraceScore(entrance)"> Edit
                <!-- <div ng-if="isbattleTree === true" class="">
                <i class="fa fa-lock"></i>
                </div> -->
                </button>
            </div>
        </div>
        <hr>
        <div class="col-xs-12 col-sm-6">
        </div>
    </div>
</div>

等其他行...

这有什么简单的解决方案吗?

2 个答案:

答案 0 :(得分:0)

似乎你得到的错误是因为你的选择器无效。在你选择的内部你写(i + 1)并期望它被计算。然而,&#34;&#34;被视为文字字符串,因此您的变量没有任何内容。您可以通过字符串连接来解决此问题,例如"div:nth-child(" + (i+1) + ")"(作为简要示例)。或者您可以使用String.format,例如String selector = String.format("div:nth-child(%d)", i+1);

答案 1 :(得分:0)

尝试使用此选项代替CSS选择器 driver.findElement(By.xpath( “HTML /体/格[3] / DIV [2] / DIV [2] / DIV [1] / DIV / DIV [5] /格[” + I +“] / DIV / DIV [1] / DIV [4] /键“))点击();