2012-12-05 37 views
2

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

下面是我想选择按钮:

<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方法选择此按钮的任何想法?

谢谢!

+0

我现在正在尝试;谢谢! – user1880633

+0

您可以使用src来查找图像。 http://stackoverflow.com/questions/3577134/searching-for-an-image-by-src-in-selenium – Prash

回答

0

试着用这个。您可以添加一些浏览器插件来获取XPath。

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

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

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

使用CSS selectors。你可以在这里找到一个简短的解释W3,以及几个例子:Examples

因此,尽量使用driver.findElement(By.cssSelector(...));

0

针对您的特殊情况下,你可以使用XPath

driver.findElement(By.xpath("//img[@alt='Place Order']")).click(); 
0

步骤1搜索基于IMG @alt属性:

与现有的DOM结构生成CSS “下订单”的选择器
图片

css = a [onclick * ='order_form' ]> img [src * ='btn_place_order.gif']

然后执行点击“下订单”图片。 ();点击();点击鼠标右键,然后点击鼠标右键,然后点击鼠标右键,在弹出的对话框中点击鼠标右键。

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> 

要查找的输入字段密码1:

WebElement passwordField1: driver.findElement(By.cssSelector("div:nth-child(3) .password-field")); 

要查找的输入字段密码2:

WebElement passwordField2: driver.findElement(By.cssSelector("div:nth-child(4) .password-field")); 

了解更多关于n-child()选择器here

相关问题