以下示例应该有帮助:
html文件:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1 class="page-header">Login</h1>
<ul class="errors"></ul>
<div>
<form class="login-form" action="checkLogin.html" method="post">
<label for="username-field">Username1</label>
<input type="text" name="username" class="username-field" />
<br />
<label for="password-field">Password1</label>
<input type="password" name="password" class="password-field" />
<br />
<input type="submit" value="Submit" />
</form>
</div>
<div>
<form class="login-form" action="checkLogin.html" method="post">
<label for="username-field">Username2</label>
<input type="text" name="username" class="username-field" />
<br />
<label for="password-field">Password2</label>
<input type="password" name="password" class="password-field" />
<br />
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
要找到 Password1 的输入字段:
WebElement passwordField1: driver.findElement(By.cssSelector("div:nth-child(3) .password-field"));
要找到 Password2 的输入字段:
WebElement passwordField2: driver.findElement(By.cssSelector("div:nth-child(4) .password-field"));
在此处了解有关 nth-child() 选择器的更多信息。