简体   繁体   中英

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).

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:

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

        fooTitle

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

FooTitle is the only thing that would change. How can I uniquely click fooButton based on what fooTitle is?

I'd recommend xpath:

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

This will find a span that contains the text fooTitle . The .. will go up to the div , then find the button that is the child of the div .

I also encountered such problem in the my project while creating scripts in selenium sometime all traditional method fails like xpath,css selector ,etc.

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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