xpath/Css select 或下面的 HTML 标签可能是什么,如何使用 Selenium xpath select 特定的单选按钮

What could be the xpath/Css selector for below HTML tag, How to select a specific radio button using Selenium xpath

  1. 下面 HTML 标签的 xpath/Css 选择器可能是什么,我的问题是如何点击 Bike.[=21 的单选按钮=]
  2. 假设下面是动态单选按钮,我们有 100 个单选按钮,这里我们无法预测单选按钮的索引号

HTML:

<table> 
    <tbody>
        <tr><td class="textAlignCenter" id="clientDocTypeSelection"><input class="marginL10" name="clientRadio" type="radio"></td><td id="clientDocTypeDescription"> Bike </td></tr>
        <tr><td class="textAlignCenter" id="clientDocTypeSelection"><input class="marginL10" name="clientRadio" type="radio"></td><td id="clientDocTypeDescription"> Car </td></tr>
    </tbody> 
</table>

找到包含您要查找的文本的 td

tds = driver.find_elements_by_xpath("//td[@class='textAlignCenter']")
for td in tds:
   if td.text == 'Bike':
      radio_input = td.find_element_by_xpath(".//input[@type='radio']")

with text as Bike you can use either of the following based 上的 click()

  • 使用Javanormalize-space():

    driver.findElement(By.xpath("//td[@id='clientDocTypeDescription' and normalize-space()='Bike']//preceding::td[1]/input")).click();
    
  • 使用Javacontains():

    driver.findElement(By.xpath("//td[contains(., 'Bike')]//preceding::td[1]/input")).click();
    

理想情况下 click() 在你需要诱导的元素上 for the elementToBeClickable() and you can use either of the following :

  • 使用Javanormalize-space():

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//td[@id='clientDocTypeDescription' and normalize-space()='Bike']//preceding::td[1]/input"))).click();
    
  • 使用Javacontains():

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//td[contains(., 'Bike')]//preceding::td[1]/input"))).click();