【问题标题】:Selenium element id not found未找到硒元素 id
【发布时间】:2016-07-11 14:31:07
【问题描述】:

我正在尝试为我的工作编写一个 Java 程序,该程序登录到 Paychex(通过 Chrome)并为我下载报告。我的代码导航到该网站,但我被困在了这一点上。我正在使用 Selenium Chrome 网络驱动程序,尽管我输入了正确的名称,但我无法找到登录字段的元素 ID。我花了几个小时试图弄清楚这一点无济于事。我尝试通过 id、name、css 和 xpath 查找元素。没有任何效果!以下是网站网址和我的代码。访问此元素的任何帮助将不胜感激。 谢谢!

WebDriver driver = new ChromeDriver();
driver.get("https://myapps.paychex.com/landing_remote/login.do?TYPE=33554433"
        + "&REALMOID=06-fd3ba6b8-7a2f-1013-ba03-83af2ce30cb3&GUID=&SMAUTHREA"
        + "SON=0&METHOD=GET&SMAGENTNAME=09PZJoiHr8jiAF1z4DL6SopY5OyRzoKSeZ4y"
        + "IhpJe7nkRdeIwtlMrg0rd7X3FRDM&TARGET=-SM-https%3a%2f%2fmyapps%2epa"
        + "ychex%2ecom%2f");    
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS)
WebElement id = driver.findElement(By.id("USER"));

HTML:

<input name="USER" class="form-control ng-pristine ng-invalid ng-invalid-required" id="USER" required="" type="text" maxlength="50" placeholder="Enter Username" data-ng-model="user.username" data-payx-form-value="siteminder.username" data-ng-change="clearShowError()" data-payx-focus="">

【问题讨论】:

  • 你的 HTML 在哪里?
  • 您确定 html 元素 id 是 USER 吗?我会在 chrome 中按 F12,你是开发者工具中的小光标图标,然后单击字段的输入框,看看它的 id 也设置了什么。
  • 抱歉 - 我这样做了,就在这里。
  • 请编辑您的问题并添加格式正确的 HTML(就像您对代码所做的那样),以便将来的读者更容易找到。

标签: java google-chrome selenium selenium-webdriver


【解决方案1】:

您确实拥有正确的 ID,但您想要的元素位于 IFRAME 中。先切换到IFRAME,然后你应该就可以访问你的元素了。

driver.get("https://myapps.paychex.com/");
driver.switchTo().frame("login");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("USER"))).sendKeys("MyUsername");
// do stuff but be sure to switch back to default content if you need to access elements outside the IFRAME
driver.switchTo().defaultContent();

【讨论】: