Home > Back-end >  How to find the element and click by it's value?
How to find the element and click by it's value?

Time:08-04

I am doing a python selenium web driver project. Here is a button, I tried various ways, xpath, name,value,type,link text methods but it didn't work. I even tried to click by class name, but becuase the other button comes first, it clicks on that instead. Unlucky.

<li >
      <input type="button" value="Uygula" onclick="btnApply();">
      <input type="button" onclick="window.location='/index.html'" value="Atla"> #I want to click this one.
</li>

I got this one also, but this is completely unrelated to this code above.

<li><a href="#"  id="editBtn" title="Düzenle" onclick="editClick('ppp1.1', 'MyISP_PTM_35')"></a></li> #I wanna click this button.

<a href="#"  id="editBtn" title="Düzenle" onclick="editClick('ppp2.1', 'MyISP_ETH')"></a>

As you can see, class, id, title all are the same. I can't click based on these. It seems there is only option that I can click through MyISP_PTM_35 thing but what is that? How to reach that?

CodePudding user response:

There are three solutions that I think of immediately:

  1. Find the element based on its value:

document.querySelectorAll("input").forEach(function(el){
  if(el.value === "Atla"){
    el.click();
  }
});
<li >
      <input type="button" value="Uygula" onclick="btnApply();">
      <input type="button" onclick="alert('Found It!')" value="Atla"> #I want to click this one.
</li>

  1. Add a unique class to the element:

document.querySelector(".foo").click();
<li >
   <input type="button" value="Uygula" onclick="btnApply();">
   <input type="button"  onclick="alert('Found It!')" value="Atla"> #I want to click this one.
</li>

  1. Instead of finding the element, just so you can click it and perform some task, just perform the task:

function foo(){
  alert("found it");
}

foo();
<li >
      <input type="button" value="Uygula" onclick="btnApply();">
      <input type="button" onclick="foo()" value="Atla"> #I want to click this one.
</li>

CodePudding user response:

Considering the HTML:

<li >
        <input type="button" value="Uygula" onclick="btnApply();">
        <input type="button" onclick="window.location='/index.html'" value="Atla"> #I want to click this one.
</li>
    

To click on the element with value as Atla you can use either of the following locator strategies:

  • Using css:

    let loginButton = driver.findElement(By.css("li.login_button input[value='Atla'][onclick*='index']"));
    await loginButton.click();
    
  • Using xpath:

    let loginButton = driver.findElement(By.name("//li[@class='login_button']//input[@value='Atla' and contains(@onclick, 'index')]"));
    await loginButton.click();
    
  • Related