繁体   English   中英

如何找到没有名称或ID的唯一按钮?

[英]How to find a unique button that has no name or id?

我有一个网页,其中包含多个容器,每个容器都有一个标题(fooHeading),名称(fooName)和一个按钮(fooButton)。

同一页上会有多个容器,如下所示:

/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
fooTitle fooButton
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

每个容器的html与以下内容相同:

<div class="fooHeading">
    <span class="fooName">

        fooTitle

    </span>
    <button class="fooButton"></button>
</div>

FooTitle是唯一会改变的东西。 如何根据fooTitle是唯一单击fooButton?

我建议使用xpath:

WebElement button = driver.findElement(By.xpath("//span[contains(text(), 'fooTitle')]/../button"));

这将找到一个包含文本fooTitlespan ..div ,然后找到作为div子级的button

我有时在硒中创建脚本时,在我的项目中也遇到了这样的问题,所有传统方法都会失败,例如xpath,css选择器等。

如果您遇到相同的情况,那么我的方法可能会帮助您,首先您必须从开始检查按钮标签的总计数,然后找到按钮计数的位置,例如其位置为pos。

List<WebElement> element = driver.findElements(By.tagName("button"));
Iterator<WebElement> itr = element.iterator();
int count=0;
WebElement e = null ;

while(itr.hasNext())
{
    count++;

    e = (WebElement) itr.next();

    if(count==pos)
        break;
}

//System.out.println(count);
//for checking total count without using break in while loop

e.click();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM