我已尽力在Selenium中为以下网站https://www.topmba.com/app编写登录脚本。这是我的代码:
public class TopMba {
String driverPath = "/usr/bin/chromedriver";
WebDriver driver;
String username = "test@gmail.com"; // Change to your username and passwrod
String password = "12345";
// This method is to navigate topmba URL
@BeforeClass
public void init() {
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.navigate().to("https://www.topmba.com");
}
// To log in topmba
@Test
public void login() {
driver.findElement(By.className("tm-user")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.switchTo().frame(driver.findElement(By.xpath("//*[@id=\"tm-modal-frame-nvtfa7vvbm\"]")));
driver.findElement(By.id("edit-user")).sendKeys(username);
driver.findElement(By.id("edit-pass")).sendKeys(password);
driver.findElement(By.id("edit-submit")).click();
driver.switchTo().defaultContent();}
@AfterClass
public void quit() {
driver.close();
}
以下是例外:
org.openqa.selenium.NoSuchElementException:没有这样的元素:无法定位元素:{“method”:“xpath”,“selector”:“// * [@ id =”tm-modal-frame-nvtfa7vvbm“ ]“}
答案 0 :(得分:0)
使用以下代码:
driver.get("https://www.topmba.com");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String parentWindowHandle = driver.getWindowHandle();
driver.findElement(By.className("tm-user")).click();
WebElement iframe = driver.findElement(By.xpath("//iframe[contains(@src,'app/sso/user/login')]"));
driver.switchTo().frame(iframe);
driver.findElement(By.id("edit-name")).sendKeys(username);
driver.findElement(By.id("edit-pass")).sendKeys(password);
driver.findElement(By.id("edit-submit")).click();
driver.switchTo().window(parentWindowHandle);
答案 1 :(得分:0)
您需要注意以下几点:
使用工具提示单击图标作为登录,您已使用过:
driver.findElement(By.className("tm-user")).click();
如果您查看HTML,此定位器策略会唯一标识该元素,但要获得更有针对性的点击,您需要定位<span>
标记内的<a>
标记它位于<li>
标记内,并带有您使用的class
属性。你粗略地诱导 WebDriverWait 。
打开登录 对话框后,您将看到登录字段位于<iframe>
内。所以你必须为这两种情况引入 WebDriverWait ,一次框架可用,并且所需的元素可以点击,你可以使用以下解决方案:
代码块:
System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.topmba.com");
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("li.tm-user>a.tmba-user>span.fa-img-icons.fa-img-user"))).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@src='/app/sso/user/login']")));
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.input-block-level.form-text.required.form-control#edit-name"))).sendKeys("khawar");
driver.findElement(By.cssSelector("input.input-block-level.form-text.required.form-control#edit-pass")).sendKeys("khawar");
driver.findElement(By.cssSelector("button.btn.btn-warning.btn-block.button.js-form-submit.form-submit#edit-submit")).click();
浏览器快照: