如何使硒单击没有ID的按钮?

时间:2019-08-23 19:29:24

标签: java selenium selenium-chromedriver

我试图单击检查元素中没有ID的按钮 这是我在页面源中搜索按钮时得到的: <input type="submit" value="Log In" onclick="this.disabled=true;this.form.submit();">

这是此链接中的“登录”按钮: https://myportal.lau.edu.lb/Pages/studentPortal.aspx

任何帮助将不胜感激。 我在Mac OS上使用Java

4 个答案:

答案 0 :(得分:2)

使用XPath表达式很简单:

String xpath = "//input[@type = 'submit' and @value = 'Log In']";
WebElement button = driver.findElement(By.xpath(xpath));

button.click();

答案 1 :(得分:1)

您需要找到其他方法来识别按钮。在这种情况下,您可以使用标签名称(“输入”)和我们在屏幕上看到的文本(“登录”)。

请尝试以下步骤:

webDriver.navigate().to("https://myportal.lau.edu.lb/Pages/studentPortal.aspx");

try {
    // Wait to make sure the page has fully loaded for this example.
    // Probably want something more sophisticated for your real test.
    Thread.sleep(5000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

// Find the button based on tag name and value attribute.
WebElement button = null;
List<WebElement> inputs = webDriver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
    if (input.getAttribute("value").equals("Log In")) {
        button = input;
        break;
    }
}

if (button == null) {
    System.err.println("Cannot find button!");
} else {
    System.out.println("Clicking button now!");
    button.click();
}

说明

在浏览器中查看此站点的源代码很有帮助。

List<WebElement> inputs = webDriver.findElements(By.tagName("input"));

此行代码搜索页面并查找标记名称为“ input”的所有元素。它与几个元素匹配,包括登录按钮以及用户名和密码字段。所以我们需要进一步缩小范围...

for (WebElement input : inputs) {

这行代码遍历上面发现的每个input。在循环内部,我们将更仔细地查看该元素,以尝试识别登录按钮。

if (input.getAttribute("value").equals("Log In")) {

正如您在原始问题中提到的那样,登录按钮具有“值”属性,其值为“登录”。其他input元素没有此属性值。因此,在这一行代码中,我们寻找一个input元素,使得value属性为“ Log In”。找到该元素后,我们便确定了该按钮,因此我们将其存储起来以便以后单击。

答案 2 :(得分:0)

如果要使用CSS来避免麻烦的问题(例如页面仍在加载且按钮尚不可用),则可以执行以下操作:

By cssLocator = By.cssSelector("input[type='submit']");
int timeout = 5000;

//wait for element to be visible, even if the page is not fully loaded ( element not in the DOM ), after the timeout it will throw an TimeoutException.
new WebDriverWait(webDriver, timeout)
        .ignoring(NoSuchElementException.class) //This is when you know that the element may not be on the screen during the loading, if you try to wait for it when it's not on the DOM, it will throw this exception.
        .until(ExpectedConditions.visibilityOfAllElementsLocatedBy(cssLocator));

WebElement loginBtn = driver.findElement(cssLocator));
loginBtn.click();

答案 3 :(得分:0)

按钮具有value attribute来唯一标识它,您可以使用按钮的value属性将其与XPath expression进行匹配,例如:

//input[@value='Log In']

enter image description here

参考文献:

相关问题