简体   繁体   中英

Selecting a checkbox based on a string in Selenium

After Entering a string into a table with a checkbox next to it, I would like to click on the checkbox. In selenium, how can i iterate through the table and search for a particular text, then check the checkbox next to it.

Here's the html of the table:

<tbody>
  <tr class="keyword-list-item">
    <td width="75%">
      <input class="keyword-selection-checkbox" type="checkbox" data-id="gw_78669090303"/>
      <span>+spatspatulalas</span>
    </td>

    <td width="25%" style="text-align: right; padding-right: 4px;">
      <span class="icon iconGoogle"/>
    </td>
  </tr>

  <tr class="keyword-list-item">
    <td width="75%">
      <input class="keyword-selection-checkbox" type="checkbox" data-id="gw_102731166303"/>
      <span>12.10 test post</span>
    </td>
    <td width="25%" style="text-align: right; padding-right: 4px;">
      <span class="icon iconGoogle"/>
    </td>
  </tr>

You can use xpath for this. Just needs be little smart how you write the xpath. Notice the following xpath find the checkbox using the text of it.

String text = "12.10 test post";
By xpath = By.xpath("//span[contains(text(),'" + text + "')]/../input");
WebElement element = driver.findElement(xpath);

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