简体   繁体   中英

Selenium Webdriver - Java - How to click checkbox based on product

I would like to click checkbox based on link text. There are several checkbox in the page so using the link text I wanted to find value of the checkbox so that I can click on the checkbox

Note # All values are dynamically generated

Can you please help correct the code to include this logic. Thanks

   driver.get(new URI(driver.getCurrentUrl()).resolve("/admin/lms/tag").toString());
   String tag_name = sheet1.getRow(j).getCell(0).getStringCellValue();
   driver.findElement(By.linkText(tag_name)).click();
   WaituntilElementpresent.isExist();
   String tag_value = sheet1.getRow(j).getCell(1).getStringCellValue();
   driver.findElement(By.cssSelector("a[href*='"+tag_value+"']")).click();
   WaituntilElementpresent.isExist();
   String product = sheet1.getRow(j).getCell(2).getStringCellValue();
   WaituntilElementpresent.isExist();
   driver.findElement(By.cssSelector("input[name='products[]'][value='11']")).click();

https://i.stack.imgur.com/mOBY2.png

You could use an xpath like this:

//tr[.//*[text()='OPIOIDMORTEPID']]//input

this means to locate the td that has this exact text and find the input from it.
If you want to use partial text then:

//tr[.//*[contains(text(), 'MORTEPID')]]//input

You can do it with the following strategy:

  1. find the link by using the link text
  2. get the parent tr element
  3. from there, find the input element of the checkbox
  4. click on the checkbox

This can be done as follows:

WebElement link = driver.findElement(By.linkText("OPIOIDMORTEPID"));
WebElement trElement = link.findElement(By.xpath("../.."));
WebElement checkboxElement = trElement.findElement(By.tagName("input"));

checkboxElement.click();

Check this out:

  1. Get a list of checkbox WebElements that have a common locator ie a common class name or tag name (this WebElement would have to have the text or be a parent of the element that has the text).

     List<WebElement> checkBoxElements = webDriver.findElements(By.cssSelector("checkbox")); 
  2. Iterate through the list and check if the WebElement has the text you are looking for. If it does, click it!

     for (WebElement e : checkBoxElements) { if (e.getText().contains("Something dynamic")) { e.click(); } } 
  3. Be happy that this works.

I would write this section as a function so that it's reusable.

public static void selectByProductName(String value)
{
    driver.findElement(By.xpath("//tr[//a[text()='" + value + "']]/td/input")).click();
}

and then call it like

selectByProductName("OPIOIDMORTEID");

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