如何找到列表中定义的按钮?

时间:2016-04-12 14:57:02

标签: css list button xpath selenium-webdriver

我正在编写一个自动化网页的selenium脚本。我需要点击列表中定义的按钮。

这是我的网络用户界面的图像 - New Account是我所指的按钮

Image

这是我的XML代码:

<div id="00B4E000000LQ2C_topNav" class="topNav primaryPalette">
  <div id="00B4E000000LQ2C_subNav" class="subNav">
    <div class="linkBar brandSecondaryBrd">
      <div id="00B4E000000LQ2C_listButtons" class="listButtons">
        <ul class="piped">
          <li>
            <input class="btn" type="button" title="New Account"       onclick="navigateToUrl('/setup/ui/recordtypeselect.jsp?ent=Account&ekp=001&retURL=%2F001%3Ffcf%3D00B4E000000LQ2C%26isdtp%3Dnv%26nonce%3Df8007ad94993912b7ff4149193a6096ccfed4ebb1454e0b9b310ad14b61de71d%26sfdcIFrameOrigin%3Dhttps%253A%252F%252Fcs83.salesforce.com&save_new_url=%2F001%2Fe%3FretURL%3D%252F001%253Ffcf%253D00B4E000000LQ2C%2526isdtp%253Dnv%2526nonce%253Df8007ad94993912b7ff4149193a6096ccfed4ebb1454e0b9b310ad14b61de71d%2526sfdcIFrameOrigin%253Dhttps%25253A%25252F%25252Fcs83.salesforce.com&isdtp=vw','LIST_VIEW','new');" name="new" value="New Account"/>
          </li>
          <li class="lastItem">
        </ul>

我用过:

driver.findElement(By.xpath(".//*[@id='00B4E000000LQ2C_listButtons']/ul/li[1]/input")).click();

(X路由萤火虫给出)但它给出了一个错误陈述

  

无法找到元素

请帮我编写脚本/找到此按钮。

2 个答案:

答案 0 :(得分:1)

您不必使用Firebug生成的XPath并在整个过程中检查元素的父项。我们可以做得更好,你可以写一个更可靠,更简单的方法来定位元素:

driver.findElement(By.name("new"));

或:

driver.findElement(By.cssSelector("input[name=new]"));

或:

driver.findElement(By.cssSelector("input[value='New Account']"));

请注意,您拥有的XPath表达式看起来有效。您可能遇到了时间问题,需要等待元素存在,可见性或可点击性,请参阅:How to wait until an element is present in Selenium?

并且,如果按钮位于iframe内,则需要切换到其上下文,然后才搜索按钮:

driver.switchTo().frame("ext-comp-1005");

答案 1 :(得分:0)

嗨,请尝试如下

// first way 
driver.findElement(By.xpath("//*[@name='new']")).click();
// second way 
driver.findElement(By.xpath("//*[@class='btn']")).click();
// basically you can use various attributes of input tag with button inside the xpath to click

更新使用i frame

// A short way to identify how many iframe's are present on a web page

List<WebElement> numberOfFrames= driver.findElements(By.tagName("iframe"));
System.out.println("Total Number of iframes present are : " +numberOfFrames.size());
for(int i=0;i<numberOfFrames.size();i++){
    // here u can identify iframes with any of its attribute vale say name,title or which is most suitable.
    System.out.println("Name of the i-frames : " + numberOfFrames.get(i).getAttribute("name"));
}

// Back to your question - button lies inside iframe hence
// key here is before clicking you have to switch to the frame first

driver.switchTo().frame(driver.findElement(By.name("frame name")));

希望这可以帮助你

相关问题