简体   繁体   English

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

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

I have a webpage that has multiple containers that each have a header (fooHeading), name (fooName), and a button (fooButton). 我有一个网页,其中包含多个容器,每个容器都有一个标题(fooHeading),名称(fooName)和一个按钮(fooButton)。

There would be multiple containers on the same page that look as follows: 同一页上会有多个容器,如下所示:

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

The html for each container looks identical to the following: 每个容器的html与以下内容相同:

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

        fooTitle

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

FooTitle is the only thing that would change. FooTitle是唯一会改变的东西。 How can I uniquely click fooButton based on what fooTitle is? 如何根据fooTitle是唯一单击fooButton?

I'd recommend xpath: 我建议使用xpath:

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

This will find a span that contains the text fooTitle . 这将找到一个包含文本fooTitlespan The .. will go up to the div , then find the button that is the child of the div . ..div ,然后找到作为div子级的button

I also encountered such problem in the my project while creating scripts in selenium sometime all traditional method fails like xpath,css selector ,etc. 我有时在硒中创建脚本时,在我的项目中也遇到了这样的问题,所有传统方法都会失败,例如xpath,css选择器等。

if same happens with you then my approach may help you first you have to check total count of button tag from starting then find the position of count of your button eg its position is pos 如果您遇到相同的情况,那么我的方法可能会帮助您,首先您必须从开始检查按钮标签的总计数,然后找到按钮计数的位置,例如其位置为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