使用WebDriver(findElement函数)

时间:2012-12-05 22:20:09

标签: webdriver

我正在编写一个使用WebDriver提交表单的Java程序。有一个方法findElement,它允许您使用类名,css选择器,id,链接文本,名称,部分链接文本,标记名称或xpath选择元素。

这是我要选择的按钮:

<div class="editable" style = "width:82px;float:right;margin-right:10px;">
<a href="#" onclick="$('order_form').submit(); return false;" class="btn">
    <img class="btn" src="/myhuds/images/rd_images/btn_place_order.gif" alt="Place Order" width="82" height="17" border="0">
</a>
</div>

我无法使用类名,因为页面上有多个按钮。关于如何使用findElement方法选择此按钮的任何想法?

谢谢!

6 个答案:

答案 0 :(得分:0)

尝试使用此功能。您可以添加一些浏览器插件来获取XPath。

     driver.findElement(By.xpath("Your XPath"));

答案 1 :(得分:0)

您可以为按钮添加ID(可能是您页面中的所有按钮),并找到 -

driver.findElement(By.id("Your ID"));

答案 2 :(得分:0)

使用CSS selectors。您可以在此处找到简短说明W3,并在此处举几个示例:Examples

因此,请尝试使用driver.findElement(By.cssSelector(...));

答案 3 :(得分:0)

对于您的特定情况,您可以使用XPath

基于img @alt属性进行搜索
driver.findElement(By.xpath("//img[@alt='Place Order']")).click();

答案 4 :(得分:0)

第1步:

使用可用的DOM结构为&#34;下订单&#34;生成CSS选择器 图像

css = a [onclick * =&#39; order_form&#39;]&gt; IMG [SRC * =&#39; btn_place_order.gif&#39;]

然后执行点击&#34;下订单&#34;图像。

driver.findElement(By.cssSelector(&#34; a [onclick * =&#39; order_form&#39;]&gt; img [src * =&#39; btn_place_order.gif&#39;]&#34 ;))点击();

答案 5 :(得分:0)

以下示例应该有所帮助:

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()选择器here